Is 0 an octal or a decimal in C? [duplicate]
I have read this. It's octal in C++ and decimal in Java. But no description about C?
Is it going to make any difference if 0 is octal or decimal? This is the question asked by my interviewer. I said no and I explained that it is always 0 regardless whether it is octal or decimal.
Then he asked why is it considered as octal in C++ and decimal in Java. I said it's the standard. Please let me know what is it in C? Will it make any difference? Why are they different in different standards?
Solution 1:
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-suffixoptdecimal-constant:
nonzero-digit
decimal-constant digitoctal-constant:
0
octal-constant octal-digithexadecimal-constant:
...
...
Solution 2:
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.
Solution 3:
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
Solution 4:
From the C Standard (6.4.4.1 Integer constants)
octal-constant:
0
octal-constant octal-digit
In fact there is no any difference for zero because zero is a common digit for octal, decimal and hexadecimal numbers. It has meaning only when a number has other digits apart from the single (leading) zero.
Take into account that there are no such integral types as decimal, octal or hexadecimal.