pad.mattdiesel.co.uk

Snippet - Default return value in C++

Default return value in C++ (Text only)

In answer to http://stackoverflow.com/questions/23068228/does-functions-have-default-return-value
Created 2014-04-14 21:22:29.286940 by Matt.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
People saying that functions with a non-void return type *must* return something are right only in theory, and by the wording of the standard. In reality, this is compiler dependant, and in most cases will compile with only a warning.

Historically with C, it would assume `int` return type. The return value would be whatever the value of the accumulator register is at that time, which could be anything, unless you actually return something. For example with g++ I can compile this code:

    #include <iostream>
    
    test() {
    }
    
    int main() {
    	std::cout << test() << std::endl;
    
    	return 0;
    }

It will compile with a warning, and it prints out: `1974484712`, or `1339600616` etc. And if you replace test with:

    test() {
    	asm("movl $123456,%%eax;" : );
    }

Then the return value is 123456. I would not rely on this behaviour when using inline assembly though.

But then again, why would you want to? Seems like a very good way to make sure your code isn't  compatible across compilers, and not as explicit in its purpose. Also, if you tried to forward declare `test()` in the above code you'd get `test();` which wouldn't compile (or make any sense). It's not any more efficient and it allows you to write code using the return value when you probably didn't mean to.

TL,DR: You could if you really wanted to, but you don't want to.