Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do statements after return change the return value?

Tags:

c++

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).

like image 496
codez Avatar asked Nov 28 '11 14:11

codez


1 Answers

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.

like image 182
Potatoswatter Avatar answered Nov 11 '22 22:11

Potatoswatter