Reputation: 1910
Consider the C code below:
#include <stdio.h>
int main()
{
int i = 012;
printf("%d", i);
}
On O/P the value of i
is printed as 10. I know (012)8 = (10)10. But I'm confused about how C stores int
variable values. Can anybody explain it to me?
Upvotes: 1
Views: 725
Reputation: 123448
All values are stored using binary representation (this is true for integers, floats, characters, etc). The value 10
(decimal) is stored as the sequence of binary digits 00000000000000000000000000001010
(assuming a 32-bit int
type).
In an assignment statement like
i = 012;
the compiler knows how to convert the string of octal digits in the literal 012
into the binary representation above. The leading 0
tells the compiler that the value is in octal representation, otherwise it would try to store the decimal value 12
(00000000000000000000000000001100
).
In the printf
statement
printf("%d\n", i);
the conversion specifier %d
tells printf
to display the value stored in i
formatted as a string of decimal digits (10
). Similarly, the conversion specifier %x
will display the value formatted as a string of hex digits (a
).
Upvotes: 0
Reputation: 2865
Hardware memory operates with bytes. So any variable (int, char, pointer, or array of those) in your program in the end will be converted to bytes. How "C" will do that again depends on hardware. See Endianness and Size of int long type.
Say you have 32-bit little-endian computer. Any 'int' in 32-bit world will be stored as four consecutive bytes in memory. That means in your case whatever literal will you use, is it either '012' or '10', it will be stored like this:
binary: 00001010 00000000 00000000 00000000
octal: 12 0 0 0
decimal: 10 0 0 0
hex: A 0 0 0
in four consecutive bytes of memory.
Upvotes: 1
Reputation: 315
To the best of my knowledge it is the C integer handler that is seeing the leading 0, and then interpreting it as base 8, or an octal constant.
Sorry for simply redirecting you, but I fear I could not say it any better than Abimaran Kugathasan in this post:
Why int j = 012 giving output 10?
For a deeper explanation, see the answer by bdonlan here: How does C Handle Integer Literals with Leading Zeros, and What About atoi?
Upvotes: -3
Reputation: 53006
They are stored in binary, you can use many representations to define them, but in the end it's the binary representation that is used.
Upvotes: 7