Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C++ function returning string

Tags:

c++

string

c++11

#include <iostream>

using namespace std;

string test(string s)
{
    string rv = "Hey Hello";
    if(s=="")
        return rv;
    else
        cout<<"Not returning"<<endl;

}

int main()
{
    string ss = test("test");
    cout<<ss<<endl;
}

The above code should not return any value and probably print garbage, but its returning "Hey Hello" even without return statement at the end in test function. Can you tell my why its behaving like this?

like image 328
Ankit Agrawal Avatar asked Mar 24 '26 13:03

Ankit Agrawal


2 Answers

reaching the end of a function returning non-void without any return statement is undefined behavior

you should have compiler warning for this kind of things if they are active

compiler are allowed to assume that undefined behavior is unreachable so the compiler have probably deleted the if statement and kept only the branch that doesn't lead to undefined behavior

like image 142
Tyker Avatar answered Mar 26 '26 04:03

Tyker


Sincerely I'm surprised that this code is compiling! You should consider the warnings as errors. Warnings are important.

My guess is that the compiler writer thought:

whenever the coder has a branch without return statement it probably means that she knows that the branch cannot be visited (for instance a precondition on the arguments is checked before calling the function) so the branch can be removed.

This could explain why the compiler behaves in this way. But a more formal answer to your question is: "this is undefined behavior, everything could happen".

When trying to compile it with gcc the output depends on the optimization level.

like image 38
jimifiki Avatar answered Mar 26 '26 02:03

jimifiki



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!