How does C Handle Integer Literals with Leading Zeros, and What About atoi?
Leading zeros indicate that the number is expressed in octal, or base 8; thus, 010 = 8. Adding additional leading zeros has no effect; just as you would expect in math, x + 0*8^n = x; there's no change to the value by making its representation longer.
One place you often see this is in UNIX file modes; 0755 actually means 7*8^2+5*8+5 = 493; or with umasks such as 0022 = 2*8+2 = 10.
atoi(nptr)
is defined as equivalent to strtol(nptr, (char **) NULL, 10)
, except that it does not detect errors - as such, atoi()
always uses decimal (and thus ignores leading zeros). strtol(nptr, anything, 0)
does the following:
The string may begin with an arbitrary amount of white space (as determined by
isspace(3)
) followed by a single optional'+'
or'-'
sign. If base is zero or 16, the string may then include a"0x"
prefix, and the number will be read in base 16; otherwise, a zero base is taken as 10 (decimal) unless the next character is'0'
, in which case it is taken as 8 (octal).
So it uses the same rules as the C compiler.
Be careful!
In this statement 005
is an octal constant.
int a = 005;
In this case it doesn't matter because a single digit octal constant has the same value as the equivalent decimal constant but in C: 015 != 15
Whether an integer literal is expressed in octal, decimal or hexadecimal, once it is parsed by the compiler it is just treated as a value. How an integer is output via printf
depends only on its type, its value and the format specifiers (and the active locale).