Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the logic behind addition of 0101 with 5 in C? [duplicate]

Tags:

c

binary

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;
}
like image 437
Uddesh Jain Avatar asked Nov 28 '22 21:11

Uddesh Jain


2 Answers

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.

like image 108
Govind Parmar Avatar answered Dec 05 '22 03:12

Govind Parmar


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.

like image 20
Niloy Rashid Avatar answered Dec 05 '22 02:12

Niloy Rashid