Is 0 an octal or a decimal in C? [duplicate] Is 0 an octal or a decimal in C? [duplicate] c c

Is 0 an octal or a decimal in C? [duplicate]


It makes little difference, but formally the integer constant 0 is octal in C. From the C99 and C11 standards, 6.4.4.1 Integer constants

integer-constant:
    decimal-constant integer-suffixopt
    octal-constant integer-suffixopt
    hexadecimal-constant integer-suffixopt

decimal-constant:
    nonzero-digit
    decimal-constant digit

octal-constant:
    0
    octal-constant octal-digit

hexadecimal-constant:
    ...
    ...


Octal.

C11 §6.4.4.1 Integer constants

octal-constant:    0    octal-constant octal-digit

And this is true since C89 §3.1.3.2.


Then he asked why is it considered as octal in C++ and decimal in Java

For sake of completeness, worth mentioning Java specs as well. From Java Language Specification 3.10.1:

DecimalNumeral:    0    NonZeroDigit Digitsopt    NonZeroDigit Underscores Digits

A decimal numeral is either the single ASCII digit 0, representing the integer zero, or consists of an ASCII digit from 1 to 9 optionally followed by one or more ASCII digits from 0 to 9 interspersed with underscores, representing a positive integer.

OctalNumeral:    0 OctalDigits    0 Underscores OctalDigits

An octal numeral consists of an ASCII digit 0 followed by one or more of the ASCII digits 0 through 7 interspersed with underscores, and can represent a positive, zero, or negative integer.

As you can see, a bare 0 is considered as decimal.Whereas any (non-empty) sequence of digits preceded by 0 is considered as octal.

Interestingly enough, from that grammar:

  • 0 is decimal
  • but 00 is octal