I don't understand why 'a' shows 23 on screen when I run it. Can anyone give me an explanation? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 027;
printf("%d",a); //23
return 0;
}
I don't understand why 'a' shows 23 on screen when I run it. Can anyone give me an explanation? Thanks in advance.
#include <stdio.h>
#include <stdlib.h>
int main()
{
int a = 027;
printf("%d",a); //23
return 0;
}
Integer constants that start with 0
are in octal representation. This means each digit represents a multiple of a power of 8, and the power of 8 associated with each digit starts at 0 for the rightmost digit and increases as you move to the left.
In the case of 027
, its value is 2*81 + 7*80 == 2*8 + 7 == 16 + 7 == 23
You initialized a with the value 027
integer numbers with a leading 0
is how you represent octal numbers in C, you can use 0x
before a number if you want to have the number in hexadecimal representation.
In the printf
function you used %d
which is used for displaying decimal numbers and it automatically converted 027
to decimal which is 23
, if you want to display the number in octal use %o
.
The preceding 0
actually refers to octal
.
Similarly, we can specify hexadecimal as well by 0x
#include <stdio.h>
int main() {
int a = 0xA;
int b = 027;
printf("%d\n", a);
printf("%d\n", b);
return 0;
}
would give:
10
23
Also, take note 0.something
is not octal
but a decimal
.