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

为什么C++代码中的fun()函数返回值为10?

Why does int d = 0012; return 10 instead of 12 in C++?

Oh, this is a super common gotcha with C++ integer literals that trips up a lot of folks! Let me break down exactly what's happening here.

First, let's look at your code again for context:

#include<bits/stdc++.h>
using namespace std;
int fun() {
    int d = 0012;
    return d;
}
int main() {
    cout << fun() << "\n";
    return 0;
}

The Core Issue: Octal Integer Literals

In C++, any integer literal that starts with a leading 0 (and isn't followed by x/X for hexadecimal) is treated as an octal (base-8) number, not the decimal (base-10) number you might expect.

So when you write 0012:

  • The leading zeros are just syntax to signal octal format (they don't add any value)
  • We convert the octal digits 12 to decimal:
    • 1 * 8^1 + 2 * 8^0 = 8 + 2 = 10

That's why the variable d ends up holding the value 10, which is what gets returned and printed.

How to Fix It

If you want to store the decimal value 12, just write it without leading zeros:

int d = 12; // This will store the decimal 12 as you'd expect

Quick Recap of Integer Literal Formats in C++

  • Decimal: No leading zeros (e.g., 12, 456)
  • Octal: Leading 0 (e.g., 012, 056)
  • Hexadecimal: Leading 0x or 0X (e.g., 0xC, 0x1A)

内容的提问来源于stack exchange,提问作者Aubdur Rob Anik

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.04.30 14:42:28