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

后端 未结 6 791
南方客
南方客 2020-12-28 18:56

Yesterday, I found myself writing code like this:

SomeStruct getSomeStruct()
{
    SomeStruct input;

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


        
6条回答
  •  爱一瞬间的悲伤
    2020-12-28 19:34

    The calling conventions for most modern CPU architectures specify a particular register to pass a function return value back to the caller. The caller makes the function call, and then uses the specified register as the return value. If you do not explicitly return a value, the caller will nonetheless use whatever garbage happens to be in that register.

    The compiler will also use all registers it has available for internal computation within the function. The register designated for holding the return value will also be used for misc computation within the function. Thus when you forget to specify a return value it is not unusual to find the correct value has miraculously been returned to the caller: the compiler used that register to store your object.

    Unfortunately even a trivial change to the function can cause the register allocation to change, so the return value becomes true garbage.

提交回复
热议问题