为什么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
12to 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
0xor0X(e.g.,0xC,0x1A)
内容的提问来源于stack exchange,提问作者Aubdur Rob Anik
相关产品推荐
相关产品推荐

