Prefixing Numeric Constants with '0' in C/C
Question:
Why does an integer constant prefixed with '0' in C/C evaluate to a different value than expected? For instance, using the constant '0123' results in the value 83 instead of 123.
Answer:
In C/C and other programming languages, numeric constants can be prefixed with different prefixes to indicate the numeric base they represent. The '0' prefix denotes an octal (base 8) constant.
When the compiler encounters a numeric constant prefixed with '0', it interprets the digits following it as an octal number. In the case of '0123', it is treated as (0 8^3) (1 8^2) (2 8^1) (3 8^0), which evaluates to 83 in decimal.
This is consistent with the C/C language specification, which states that a numeric constant starting with '0' is treated as an octal number. This rule applies to both integer and floating-point constants.
Understanding the role of numeric prefixes is crucial for accurately representing and interpreting numeric data in C/C programs.
The above is the detailed content of Why does `0123` evaluate to 83 in C/C ?. For more information, please follow other related articles on the PHP Chinese website!