| Topic: |
DEVELOP > c-Plus-Plus |
| User: |
"Chinmoy Mukherjee" |
| Date: |
14 Jun 2005 12:20:59 AM |
| Object: |
newbies question about return value |
Hi All,
If I have a function
std::string f() {
std::string tmpString = "Error"
return tmpString
}
main() {
std::string returnString = f();
cout << returnString << endl; //Will the output be Error , or blank?
how do I circumvent the problem
}
Regards,
Chinmoy
.
|
|
| User: "Srini" |
|
| Title: Re: newbies question about return value |
14 Jun 2005 01:48:14 AM |
|
|
Hi All,
Hi
If I have a function
std::string f() {
std::string tmpString = "Error"
return tmpString
}
main() {
std::string returnString = f();
cout << returnString << endl; //Will the output be Error , or blank?
how do I circumvent the problem
}
I don't see any problem. The returned string is assigned to the string
obj in main by invoking the assignment operator. So the output will be
'Error'...
Regards,
Chinmoy
Well, not meaning to be harsh - but you could have tried it on some
compiler yourself!
Srini
.
|
|
|
|
| User: "Jim Langston" |
|
| Title: Re: newbies question about return value |
15 Jun 2005 01:33:27 PM |
|
|
Hi All,
If I have a function
std::string f() {
std::string tmpString = "Error"
return tmpString
}
main() {
std::string returnString = f();
cout << returnString << endl; //Will the output be Error , or blank?
how do I circumvent the problem
}
Regards,
Chinmoy
The output will be error. The reason is you are returning the std::string
by value, not by pointer,
so a temp copy gets made and passed back.
Same as if you had did this:
int f()
{
int i = 10;
return i;
};
int main()
{
int MyInt = f();
std::cout << MyInt << std::endl; // Output will be 10
}
the integer value 10 is actually returned, not a pointer to i.
Same with returning the std::string, the value is returned, not a pointer to
it.
I'm not sure, but I think that the value of the std::string gets returned on
the stack.
.
|
|
|
|
| User: "Jaspreet" |
|
| Title: Re: newbies question about return value |
14 Jun 2005 02:32:02 AM |
|
|
Chinmoy Mukherjee wrote:
Hi All,
If I have a function
std::string f() {
std::string tmpString = "Error"
return tmpString
Semicolon at end of each line. Pls copy paste your code properly.
}
main() {
std::string returnString = f();
cout << returnString << endl; //Will the output be Error , or blank?
Output would be Error. Try it yourself.
how do I circumvent the problem
What problem do you have ?
}
Regards,
Chinmoy
.
|
|
|
|
| User: "Jacques Labuschagne" |
|
| Title: Re: newbies question about return value |
14 Jun 2005 02:33:19 AM |
|
|
Chinmoy Mukherjee wrote:
cout << returnString << endl; //Will the output be Error , or blank?
Why do you think it will print anything other than "Error"? (Ignoring
your missing semi-colons.)
Jacques.
.
|
|
|
|

|
Related Articles |
|
|