开发者

Why is initializing an integer in C++ to 010 different from initializing it to 10?

开发者 https://www.devze.com 2023-03-12 23:57 出处:网络
When an integer is initialized as int a = 010, a is actually set to 8, but开发者_StackOverflow中文版 for int a= 10, a is set to 10.

When an integer is initialized as int a = 010, a is actually set to 8, but开发者_StackOverflow中文版 for int a = 10, a is set to 10. Can anyone tell me why a is not set to 10 for int a = 010?


Because it's interpreting 010 as a number in octal format. And in a base-8 system, the number 10 is equal to the number 8 in base-10 (our standard counting system).

More generally, in the world of C++, prefixing an integer literal with 0 specifies an octal literal, so the compiler is behaving exactly as expected.


0 before the number means it's in octal notation. So since octal uses a base of 8, 010 would equal 8.

In the same way 0x is used for hexadecimal notation which uses the base of 16. So 0x10 would equal 16 in decimal.


In C, C++, Objective C and related languages a 0 prefix signifies an octal literal constant, so 010 = 8 in decimal.


Leading 0 in 010 means that this number is in octal form. So 010 means 8 in decimal.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号