In C, storing values ​​starting at zero becomes mutated, why?

For instance:

int main(){ int x = 01234567; printf("\n%d\n",x); return 0; } 

The following code creates: 342391

If I did not include 0 at the beginning, the value of x would be 1234567, why does C save the value in this way, and is there a way to get it out of it?

+4
source share
4 answers

Because numbers starting with 0 are represented as octal numbers . You cannot really change this behavior, just do not include zero at the beginning.

+12
source

Numeric constants starting with 0 are interpreted as base 8.

+8
source

Integer constants written with a leading 0 are interpreted as octal (base-8), not decimal (base-10). This is similar to 0x triggering a hexadecimal (base-16) interpretation.

Basically, everything you can do here does not put leading 0s on your integer constants.

+7
source

At compile time, the C compiler identifies any integer literals in your code, and then interprets them using a set of rules to get their binary value for use by your program:

  • Base-16 (hexadecimal) - Any integer literals starting with '0x' will be treated as a hexadecimal value. So int x = 0x22 gives x decimal value 2 * 16^1 + 2 * 16^0 = 34 .
  • Base-8 (Octal) - Any integer literals starting with '0' will be treated as octal values. So int x = 022 gives x decimal value 2 * 8^1 + 2 * 8^0 = 18 .
  • Base-10 (Decimal) - any integer literals that do not match the other two rules will be treated as a decimal value. So int x = 22 gives x decimal value of 22 .

It should be noted that GCC supports an extension that provides another rule for specifying binary integers. In addition, these specification methods are supported only for integer literals at compile time.

+3
source

Source: https://habr.com/ru/post/1382736/


All Articles