Is 0 a decimal literal or an octal literal?

半腔热情 提交于 2019-11-26 11:37:27

Yes, 0 is an Octal literal in C++.

As per the C++ Standard:

2.14.2 Integer literals [lex.icon]

integer-literal:  
    decimal-literal integer-suffixopt  
    octal-literal integer-suffixopt  
    hexadecimal-literal integer-suffixopt  
decimal-literal:  
    nonzero-digit  
    decimal-literal digit  
octal-literal:  
    0                           <--------------------<Here>
    octal-literal octal-digit

Any integer value prefixed with 0 is an octal value. I.e.: 01 is octal 1, 010 is octal 10, which is decimal 8, and 0 is octal 0 (which is decimal, and any other, 0).

So yes, '0' is an octal.

That's plain English translation of the grammar snippet in @Als's answer :-)


An integer prefixed with 0x is not prefixed with 0. 0x is an explicitly different prefix. Apparently there are people who cannot make this distinction.

As per that same standard, if we continue:

 integer-literal:
     decimal-literal integer-suffixopt
     octal-literal integer-suffixopt
     hexadecimal-literal integer-suffixopt
 decimal-literal:
     nonzero-digit                       <<<---- That's the case of no prefix.
     decimal-literal digit-separatoropt digit
 octal-literal:
     0                                    <<<---- '0' prefix defined here.
     octal-literal digit-separatoropt octal-digit <<<---- No 'x' or 'X' is
                                                          allowed here.
 hexadecimal-literal:
     0x hexadecimal-digit                 <<<---- '0x' prefix defined here
     0X hexadecimal-digit                 <<<---- And here.
     hexadecimal-literal digit-separatoropt hexadecimal-digit
MCG

Apparently all integer literals starting with zero are in fact octal. This means that it includes 0 as well. This makes little difference since zero is zero. But not knowing this fact can hurt you.

I realized this when I was trying to write a program to convert binary numbers to decimal and hexidecimal output. Everytime that I was giving a number starting with zero I was getting the wrong output (For example, 012 = 10, not 12).

It's good to know this information so you don't make the same mistake.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!