One of my friends asked me the output of this code and I just got shocked after running this code. The output of this code is 70. Please explain why?
#include <stdio.h>
int main()
{
int var = 0101;
var = var+5;
printf("%d",var);
return 0;
}
One of my friends asked me the output of this code and I just got shocked after running this code. The output of this code is 70. Please explain why?
#include <stdio.h>
int main()
{
int var = 0101;
var = var+5;
printf("%d",var);
return 0;
}
The C Standard dictates that a numeric constant beginning with 0 is an octal constant (i.e. base-8) in § 6.4.4.1 (Integer constants).
The value 101 in base 8 is 65 in base 10, so adding 5 to it (obviously) produces 70 in base 10.
Try changing your format specifier in printf
to "%o"
to observe the octal representation of var
.
It is because of Integer Literals. A number with leading 0
denoted that the number is an octal number. You can also use 0b
for denoting binary number, for hexadecimal number it is 0x
or 0X
. You don't need to write any thing for decimal. See the code bellow.
#include<stdio.h>
int main()
{
int binary = 0b10;
int octal=010;
int decimal = 10;
int hexa = 0x10;
printf("%d %d %d %d\n", octal, decimal, hexa, binary);
}
For more information visit tutorialspoint.
Not shocking at all. C11 Standard - 6.4.4.1 Integer constants(p3) provides:
"An octal constant consists of the prefix 0 optionally followed by a sequence of the digits 0 through 7 only."
Some compilers, such as gcc, provide extension for specifying binary constants, e.g. GCC Manual - 6.64 Binary Constants using the ‘0b’ Prefix But note, this is a non-standard extension.
Combining both in your example would give:
#include <stdio.h>
int main (void) {
int var = 0101,
bar = 0b0101;
var = var + 5;
bar = bar + 5;
printf ("var: %d\nbar: %d\n", var, bar);
return 0;
}
Example Use/Output
$ ./bin/octbin
var: 70
bar: 10
Inicially var is in octal numeric system, so var=0101
is equal to 001000001
in binary system or equal to 65
in decimal system.
for example in this code you can show 65
as the var inicial value.
#include <stdio.h>
int main()
{
int var = 0101;
printf("initial value. var=%o\n",var);
var = var+5;
printf("result of var+5. var=%d\n",var);
printf("%d\n",var);
return 0;
}
You'll get this output:
initial value. var=65
result of var+5. var=70
70