Invictus
Invictus

Reputation: 2780

what is the return value of the function that returns int, but isn't returning anything explicitly. for instance output of

int fun()
{
 printf("\ncrap");
}


void main()
{
  printf("\n return value of fun %d", fun());
}

and please, can you explain on how the stack allocates the memory for return values and how the stack works here.

Upvotes: 1

Views: 172

Answers (3)

Didier Trosset
Didier Trosset

Reputation: 37467

As it is architecture dependant, there is no general thing.

However, it can be admitted that the value that is computed last, or the returned value from the last called function can be returned. But in the end it is undefined behavior. If you want to rely on it ...

Note also that there is a special case for int main(). (Btw: void main() is not standard.) If no return statement is present, it returns 0.

Upvotes: 2

Kerrek SB
Kerrek SB

Reputation: 477464

fun triggers undefined behaviour.

Please always compile with all compiler warnings enabled. That should give you a warning that you are making that very mistake.

Your main is also triggering undefined behaviour because the C++ standard demands that there be only one single function called main and it return int. However, you are allowed, as a special case, to omit the return statement in your (corrected) main function.

"The stack", as you presume, is not part of the C++ language. But that's irrelevant; the standard says that the returned object is constructed in the scope of the caller, which is all you need to know.

(Practically, an unreturned int is probably going to end up like an uninitialized variable of type int, but the standard says that the function call already triggers the undefined behaviour, not just read-access later on.)

Upvotes: 3

David Heffernan
David Heffernan

Reputation: 613422

That's undefined behaviour. Anything could happen.

Upvotes: 2

Related Questions