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

  • A+
Category:Languages

This question already has an answer here:

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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: