You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

未添加return语句的int类型函数为何能运行并输出4?

Why Your 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 int function is stored in the EAX register.
  • For 64-bit systems, it’s stored in the RAX register.

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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.07 18:32:52