Search code examples
pointersreturncodeblocks

Object returned without return keyword


I was trying something out, and I made this code: http://cpp.sh/4x435 (Shown here below too)

#include <iostream>

using namespace std;

class Thing{
    public:
        int height;
        Thing(int h): height(h) {};
        Thing(): height(10) {};
        ~Thing(){};

        int display(){ return this->height; }
};

Thing* get(){
    Thing* x = new Thing(33);
}

int main(){
    Thing* a = new Thing();
    std::cout<<"1: "<<a->display()<<std::endl;
    a = get();
    std::cout<<"2: "<<a->display()<<std::endl;
    return 0;
}

I forgot to add a return in the "get"-function before I compiled and ran it, surprisingly it played out correctly anyway(i.e. "1: 10, 2: 33" was the output).

Now I saw that in the shell online it only displays "1: 10", whereas when I try having it return an int or string by value, like so:

int get(){ int a = 30; }

int main(){
    int b = get();
    std::cout<<"1: "<<b<<std::endl;
    return 0;
}

it doesn't function correctly(outputs "1: 1"), this is expected.

What's happening there? Shouldn't "Things* get()" malfunction, cause an error or at least make it spit out some gibberish onto the screen or something?

I'm using Code::Blocks 16.01, C++11, GNU GCC Compiler, no extra flags set(so only any already set by Code::Blocks)

EDIT:

It's not exactly the same as the suggested duplicate, because the example of int get() { int a = 30; } returns 1, had it returned 30, then it would have been the same problem.

However, I tried this:

int* get(){
    int* x = new int(4);
}
int main(){
    int* a;
    a = get();
    std::cout<<"2: "<<*a<<std::endl;
    return 0;
}

And here I get the same problem that I found when trying the first version of the code where get() was of the return type Thing*. So it seems like it has to do with pointers.


Solution

  • Use the -Wall option when compiling to have an appropriate warning, like:

    gcc program.c -o program -Wall
    

    Otherwise this question and its accepted answer explains why it happens, even providing an example similar to your observation:

    Why does flowing off the end of a non-void function without returning a value not produce a compiler error?

    If you are curious, check the assembler output! You can generate it by:

    gcc program.c -S
    

    Since the behavior is undefined, anything may happen, what you are experiencing is most likely caused by that within the function, the compiler left the right value in the register normally used for returning.