Grigor
Grigor

Reputation: 107

What is special about numbers starting with zero?

This is kinda stupid question, but it's interesting for me )

This is what i get with visual studio 2013

int i = 07;     // i == 7
int i = 16;     // i == 16
int i = 00016;  // i == 14, why?
int i = 05016;  // i == 2574, wow )
int i = 08;     // compile error, compiler expects octal number...

If number starts with zero and contains 8, it's compile error. Is this normal? And what exactly compiler does with starting zeros if 00016 == 14?

Thanks to all ))

Upvotes: 8

Views: 12353

Answers (4)

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385264

Yes, this is expected.

[C++11: 2.14.2/1]: An integer literal is a sequence of digits that has no period or exponent part. An integer literal may have a prefix that specifies its base and a suffix that specifies its type. The lexically first digit of the sequence of digits is the most significant. A decimal integer literal (base ten) begins with a digit other than 0 and consists of a sequence of decimal digits. An octal integer literal (base eight) begins with the digit 0 and consists of a sequence of octal digits.22 A hexadecimal integer literal (base sixteen) begins with 0x or 0X and consists of a sequence of hexadecimal digits, which include the decimal digits and the letters a through f and A through F with decimal values ten through fifteen. [ Example: the number twelve can be written 12, 014, or 0XC. —end example ]

22 The digits 8 and 9 are not octal digits.

Upvotes: 15

user308323
user308323

Reputation:

An integer literal that starts with 0 is an octal number, much like a number starting with 0xis a hexadecimal number.

Octal numbers can only contain the digits 0 to 7, and this is why you get a compilation error.

Upvotes: 7

davidc
davidc

Reputation: 132

Starting a number with 0 makes it Octal, so digits 8 and 9 are illegal, and your other examples show conversion to decimal.

Upvotes: 3

Kerrek SB
Kerrek SB

Reputation: 477358

Integer literals that start with 0 are octal literals. Therefore they must only contain the digits 0–7.

(Amusingly, this includes the literal 0 itself.)

Upvotes: 5

Related Questions