When you create an integer with leading zeros, how does C handle it? Is it different for different versions of C?
In my case, they just seem to be dropped (but maybe that is what printf does?):
#include <stdio.h>
int main() {
int a = 005;
printf("%i\n", a);
return 0;
}
I know I can use printf to pad with 0s, but I am just wondering how this works.
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 tostrtol(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:So it uses the same rules as the C compiler.