1

The following code prints 255, but if I assigned 0255 to x, as in the second line, the code prints 173!

Is there any explanation for this?

void main()
{
    unsigned long x = 255;
    /* unsigned long x = 0255;*/
    unsigned char *ptr = &x;
    printf("%u",*ptr);
    getch();
}
Ahmed Akhtar
  • 1,444
  • 1
  • 16
  • 28
YaserM
  • 185
  • 2
  • 9

2 Answers2

3
unsigned char x = 0255;

0255 is considered an octal int literal. This works because you can assign int literals to chars, and octal 0255 is (5*8^0)+(5*8^1)+(2*8^2) = 173 in decimal notation.

Visit the reference for more info on what the different forms of notational string literals are, but for quick reference:

unsigned char x = 0255; // Octal -> 173 in decimal
unsigned char x = 255; // Decimal -> 255 in decimal
unsigned char x = 0x2F // Hexadecimal -> 47 in decimal
Magisch
  • 7,312
  • 9
  • 36
  • 52
2

When a number has a '0' in front of other digits, it's treated as an octal number. And 255 in octal is 173 in decimal.

ForceBru
  • 43,482
  • 10
  • 63
  • 98