未添加return语句的int类型函数为何能运行并输出4?
quadrato1 Function Returns 4 Without a return Statement Great question! Let’s unpack this weird (and risky) behavior step by step.
First: This is Undefined Behavior
The C++ standard explicitly states that if you call a non-void function that doesn’t have a return statement, the result is undefined behavior. That means the compiler can do literally anything—your program might output the "right" value, crash, print garbage, or even behave differently every time you run it. The fact that it outputs 4 here is pure coincidence, not a feature.
Why You Got 4 Specifically
Most compilers (like GCC, Clang, or MSVC) follow standard calling conventions for returning integer values:
- For 32-bit systems, the return value of an
intfunction is stored in theEAXregister. - For 64-bit systems, it’s stored in the
RAXregister.
Looking at your quadrato1 function:
int quadrato1(int a) { a = a * a; }
When you compute a * a (2 * 2 = 4), the CPU stores this result temporarily in the EAX/RAX register before assigning it back to a. Since your function doesn’t have a return statement, the compiler doesn’t overwrite this register before exiting the function.
When main calls quadrato1(x) and assigns the result to y, it reads whatever value is in the register used for return values. In this case, it’s still the 4 from your multiplication—so you get the expected output by accident.
This Won’t Always Work!
If you modify the function even slightly, the result will break. For example:
int quadrato1(int a) { a = a * a; cout << "Hello"; // This call will overwrite the EAX/RAX register }
Now y will probably hold some random value, because the cout call uses the same register for its own internal operations.
The Takeaway
Never rely on this behavior! Always add a proper return statement to non-void functions. Your corrected function should look like this:
int quadrato1(int a) { a = a * a; return a; // Explicit return statement }
内容的提问来源于stack exchange,提问作者Federica Guidotti

