C programming automatic octal interpretation

后端 未结 1 1255
感情败类
感情败类 2021-01-28 01:23

Code 1:

int a = 0987654321;
printf(\"%d\",a);

Code 2:

int a;
scanf(\"%d\",&a);
printf(\"%d\",a);

Here if

相关标签:
1条回答
  • 2021-01-28 02:11

    There are multiple representations which you can use when writing code with C -

    • Hexadecimal (0x123A)
    • Binary (0b1011) -- Is not supported by standard C but is an extension provided by compilers like gcc.
    • Octal (01237)
    • Decimal (1234) -- perhaps the most common.

    What you are using here is the octal representation (because it starts with a 0). Meaning each of the digit is base 8. As a result each of the digit after the 0 can only be in the range [0-7]. 9 is not a valid octal digit and hence the compiler is complaining.

    If you want to actually use the decimal representation you can remove the 0 as -

    int a = 987654321;
    

    In the second example it actually works fine because scanf with %d always scans as a decimal representation and 9 is a valid decimal digit.

    0 讨论(0)
提交回复
热议问题