Home  >  Article  >  Backend Development  >  Why does "0123" print as "83" in C/C ?

Why does "0123" print as "83" in C/C ?

DDD
DDDOriginal
2024-11-14 18:24:02927browse

Why does

Understanding Numeric Constants with Leading Zeros in C/C

In C/C , numeric constants can be prefixed with a leading '0' to indicate their base or number system. This prefix signifies that the constant is an octal (base 8) value.

When you used '0123' as an integer constant, the compiler interprets it as an octal value. In the octal number system, '123' represents the decimal value 83 (881 3). Therefore, when you print the value, it outputs 83 instead of 123.

This behavior is consistent across C and C compilers, such as GCC. It also applies to floating-point constants prefixed with '0', although the conversion rules may differ slightly.

To explicitly specify the base of a numeric constant, you can use the following prefixes:

  • '0': Octal (base 8)
  • '0x' or '0X': Hexadecimal (base 16)
  • No prefix: Decimal (base 10)

For example, to represent the decimal value 123 as an octal constant, you would use '0123'. Conversely, to represent the octal value 83 as a decimal constant, you would use 83.

The above is the detailed content of Why does "0123" print as "83" in C/C ?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn