codez
codez

Reputation: 1391

Why do statements after return change the return value?

C++ returns invalid value in the following code:

#include <iostream>
#include <vector>

using namespace std;

int f(){
    vector< int * > v[2];
    return 1;
    v[1].push_back(NULL);
}

int main(){
    cout << f();
}

The output is:

205960

When I commnet line after return, it works fine:

#include <iostream>
#include <vector>

using namespace std;

int f(){
    vector< int * > v[2];
    return 1;
    //v[1].push_back(NULL);
}

int main(){
    cout << f();
}

The output is:

1

I am using code::blocks with mingw32-g++.exe compiler. The mingw version is: gcc version 4.4.1 (TDM-2 mingw32).

Upvotes: 6

Views: 233

Answers (1)

Potatoswatter
Potatoswatter

Reputation: 137770

Your compiler has a bug. Fortunately, it is also obsolete. You should upgrade — G++ is up to version 4.6.2, which also implements much of C++11, which is very useful.

If you choose to stick with an older compiler, that is also a decision to accept its flaws.

Edit: If you are really stuck with 4.4 (for example due to a PHB), that series is still maintained. You can upgrade to GCC 4.4.6, released just this past April.

Upvotes: 10

Related Questions