-1

Newbie programmer here! I recently started learning about C and was making a small code about declaring an integer variable called "age" then printing it. Something like as follows:

#include<stdio.h>

int main(){
    int age = 027;
    int scnd_age = 27;
    printf("My age is: %d\n", age);
    printf("My age is: %d",scnd_age);
    return 0;
}

To my surprise the output both times was totally different.first line says 23 while 2nd says 27

I've only used python in the past and I know it produces an error if you try to declare an integer variable which starts with 0, but I am curious why is it legal to do it in C and why does it gives different outputs?

Was trying to declare an integer variable called "age" then print it.

Tried storing both 27 and 027 in the said variable and surprisingly both times it printed different results.

  • 3
    027 is base 8, 27 is base 10. Different numbers. – Shawn Aug 19 '23 at 07:32
  • Both _octal_ and _hexadecimal_ are _usually_ considered to be "_unsigned_" even though you're assigning `027` to a signed integer variable. Better to use `unsigned int age = 027`... – Fe2O3 Aug 19 '23 at 07:54
  • AND, since you know know that `027` is an _octal_ value, the correct format string to print it would be: `printf( "My age is: %o", age );` – Fe2O3 Aug 19 '23 at 08:00
  • 2
    @Fe2O3 `027` and `0x27` are *signed* integer constants, not unsigned. They are often used in a context that requires an unsigned value, and in many of those cases they are automatically cast to an unsigned type, but `027` is equivalent to `23`, not `23u`. If you want an unsigned octal constant, use `027u`. You can easily see this by comparing `03 > -5` with `03u > -5`. The first is is `1`, since it uses signed comparison, while the second is `0`, since it uses unsigned comparison. – Tom Karzes Aug 19 '23 at 08:37
  • @TomKarzes Thank you for that... Just wanted to point out that _octal_ values are often used in situations that are unsigned... All part of the learning experience... – Fe2O3 Aug 19 '23 at 08:51
  • @TomKarzes -- `027` and `0x27` are signed integer constants because these values will always fit in an `int`, but for unsuffixed octal or hexadecimal integer constants whose values will not fit in an `int` the type [may be signed or unsigned](https://stackoverflow.com/questions/76843218/what-is-difference-in-assigning-hex-or-decimal-value-to-uint16-t/76843330#76843330). This differs from unsuffixed decimal constants which are always signed. – ad absurdum Aug 19 '23 at 14:19
  • @adabsurdum That's a good point. My comment applied to small values which would fit in either. – Tom Karzes Aug 19 '23 at 14:43

0 Answers0