Home > Backend Development > C++ > body text

Why does `0123` evaluate to 83 in C/C ?

Barbara Streisand
Release: 2024-11-18 10:13:02
Original
708 people have browsed it

Why does `0123` evaluate to 83 in C/C  ?

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!

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