Home > Backend Development > C++ > body text

Why does '0123' equal 83 in C/C ?

Mary-Kate Olsen
Release: 2024-11-17 04:55:03
Original
221 people have browsed it

Why does '0123' equal 83 in C/C  ?

Understanding Numeric Constant Prefixes in C/C

When writing numeric constants in C/C , the prefixes used before the numbers carry significant meaning that can alter the interpreted value. One such prefix is '0', which represents an octal (base-8) constant.

Consider the case when the numeric constant '0123' was assigned to an integer variable. In base-10 (decimal), this value would indeed represent 123. However, because it's prefixed with '0', it's interpreted as an octal constant.

In the binary representation of an octal digit, each digit has a specific value:

  • 0: 000
  • 1: 001
  • 2: 010
  • 3: 011
  • 4: 100
  • 5: 101
  • 6: 110
  • 7: 111

As '0123' is an octal constant, we can convert each digit to its binary equivalent:

  • 0: 000
  • 1: 001
  • 2: 010
  • 3: 011

Concatenating these binary digits, we get: 000001001011. Converting this to base-10 (decimal) gives us the value 83.

Therefore, when a numeric constant in C/C is prefixed with a '0', it signifies an octal constant, and the value is interpreted accordingly. This behavior is consistent across both C and C with the GCC compiler and even for floating-point constants.

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

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template