Mark Berube
Mark Berube

Reputation: 204

In C storing values that start with zero get mutated, why?

For example:

int main(){

    int x = 01234567;

    printf("\n%d\n",x);

    return 0;

}

The following code produces: 342391

If I didn't include the 0 at the beginning, the value x would be 1234567, why does C store the value this way and is there any way to get it from not doing this?

Upvotes: 4

Views: 4989

Answers (4)

Peter R
Peter R

Reputation: 414

At compile time a C compiler will identify any integer literals in your code and then interpret these via a set of rules to get their binary value for use by your program:

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

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

Upvotes: 5

bdonlan
bdonlan

Reputation: 231283

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

Basically all you can do here is not put leading 0s on your integer constants.

Upvotes: 7

drdwilcox
drdwilcox

Reputation: 3951

Numeric constants beginning with a 0 are interpreted as base 8.

Upvotes: 8

Karel Petranek
Karel Petranek

Reputation: 15164

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

Upvotes: 13

Related Questions