c++stackstack-trace

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.


Solution

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