newbies question about return value

C

Chinmoy Mukherjee

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
 
S

Srini

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
 
J

Jaspreet

Chinmoy said:
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.
 
J

Jim Langston

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.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,744
Messages
2,569,484
Members
44,903
Latest member
orderPeak8CBDGummies

Latest Threads

Top