1

Got confused with the following peice of code.

#include <stdio.h>
void main()
{
int a=0100;
printf("%x",a);
}

The value I am getting is 40.

Can someone explain me whats going on here?

Note : When I removed the digit 0 before digit 1 then its coming 64 which is correct, when 100 is converted into hex.

Codepad link to above code

Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79
roxid
  • 493
  • 4
  • 14

4 Answers4

2

In C, a constant prefixed with a 0 is an octal constant. 0100 in base 8 is 1000000 in base 2, which is 40 in hexadecimal, which is 64 in base 10. So your program is printing exactly what it should.

  • Thank you so much. – roxid Nov 06 '16 at 12:28
  • but we are assigning the value of 0100 to integer data type a. Then why the conversion to octal? – roxid Nov 06 '16 at 12:30
  • 1
    The C compiler treats any numeric constant starting with `0` as an octal value. The integer variable doesn't care about the numeric base of the constant in the source code - everything in the computer is stored in base 2 (binary) anyways, so whether the numeric constant in the source code is base 10, or base 8, or base 16 makes no difference. – Bob Jarvis - Слава Україні Nov 06 '16 at 12:33
1

Here

int a=0100;

you are assigning an octal value, which is 64 in base 10 and 40 is hex.

An integer literal starting with a 0 is octal in C.

P.P
  • 117,907
  • 20
  • 175
  • 238
1

a 0 prefix in c means octal, not decimal.

http://en.cppreference.com/w/cpp/language/integer_literal

  • decimal-literal is a non-zero decimal digit (1, 2, 3, 4, 5, 6, 7, 8, 9), followed by zero or more decimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9)
  • octal-literal is the digit zero (0) followed by zero or more octal digits (0, 1, 2, 3, 4, 5, 6, 7)
  • hex-literal is the character sequence 0x or the character sequence 0X followed by one or more hexadecimal digits (0, 1, 2, 3, 4, 5, 6, 7, 8, 9, a, A, b, B, c, C, d, D, e, E, f, F)
  • binary-literal is the character sequence 0b or the character sequence 0B followed by one or more binary digits (0, 1)
Shloim
  • 5,281
  • 21
  • 36
1

0100 is a octal value as it has prefix 0.

0100 in octal (base 8)
 ^~~~(8^2)*1

is same as  

0x40  in hexadecimal (base 16)
  ^~~~(16^1)*4   // %x is for hexadecimal format

is same as 

64 in decimal (base 10)

printf("%o %x %d",a, a, a);  // prints 100 40 64
Saurav Sahu
  • 13,038
  • 6
  • 64
  • 79