Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What happens if you don't return a value in C++?

Yesterday, I found myself writing code like this:

SomeStruct getSomeStruct()
{
    SomeStruct input;

    cin >> input.x;
    cin >> input.y;
}

Of course forgetting to actually return the struct I just created. Oddly enough, the values in the struct that was returned by this function got initialized to zero (when compiled using g++ that is). Is this just a coincidence or did another SomeStruct get created and initialized somewhere implicitly?

like image 831
Jason Baker Avatar asked Nov 16 '08 04:11

Jason Baker


People also ask

Do you always need a return in C?

Yes. Always do a clean return from any non-void function.

What happens if you dont return 0 in C?

Short Answer: Nothing. Better Answer: return 0 it's used in main like a signal for know the exit of program was a success when return 0 executes. Best Answer: Still nothing because compilers already "put" return 0 in the the end of your code if you not explicit.

Can you return nothing in C?

In C there are no subroutines, only functions, but functions are not required to return a value. The correct way to indicate that a function does not return a value is to use the return type "void". ( This is a way of explicitly saying that the function returns nothing. )


1 Answers

Falling off the end of a function that is declared to return a value (without explicitly returning a value) leads to undefined consequences. For gcc, you should start with the -Wall command line switch that turns on most useful warnings. The specific gcc warning that controls the warning you want is -Wreturn-type (which is included in -Wall, I just mention this for completeness).

Once you have warnings turned on, you should also use -Werror to treat warnings as errors and make the build stop at the point it detects an error.

like image 87
Greg Hewgill Avatar answered Sep 28 '22 20:09

Greg Hewgill