1

I don't understand why 'a' shows 23 on screen when I run it. Can anyone give me an explanation? Thanks in advance.

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int a = 027;
    printf("%d",a); //23

    return 0;
}

3 Answers3

2

Integer constants that start with 0 are in octal representation. This means each digit represents a multiple of a power of 8, and the power of 8 associated with each digit starts at 0 for the rightmost digit and increases as you move to the left.

In the case of 027, its value is 2*81 + 7*80 == 2*8 + 7 == 16 + 7 == 23

dbush
  • 205,898
  • 23
  • 218
  • 273
  • Each **position** is associated with a power of eight. Each **digit** denotes a multiple of the power of eight for its position. The digit does not represent a power of eight. For example, in `027`, `2` denotes 16, which is not a power of eight, and `7` denotes seven, which is not a power of eight. Remember, **you** know what you mean, but people who are just learning do not—they do not have the information needed to figure out the non-literal meaning of your words. Telling them that something represents a thing it does not could be confusing. – Eric Postpischil Nov 21 '19 at 15:55
  • @EricPostpischil Good catch, as always. Updated. – dbush Nov 21 '19 at 16:00
2

You initialized a with the value 027 integer numbers with a leading 0 is how you represent octal numbers in C, you can use 0x before a number if you want to have the number in hexadecimal representation. In the printf function you used %d which is used for displaying decimal numbers and it automatically converted 027 to decimal which is 23, if you want to display the number in octal use %o.

Etheraex
  • 508
  • 6
  • 17
1

The preceding 0 actually refers to octal.

Similarly, we can specify hexadecimal as well by 0x

#include <stdio.h>

int main() {
    int a = 0xA;
    int b = 027;
    printf("%d\n", a);
    printf("%d\n", b);
    return 0;
}

would give:

10
23

Also, take note 0.something is not octal but a decimal.

Ankit Sharma
  • 1,626
  • 1
  • 14
  • 21