Home >Backend Development >C++ >Why Do Zero-Prefixed Numbers Behave Unexpectedly in C ?

Why Do Zero-Prefixed Numbers Behave Unexpectedly in C ?

Barbara Streisand
Barbara StreisandOriginal
2024-12-07 14:50:17507browse

Why Do Zero-Prefixed Numbers Behave Unexpectedly in C  ?

Understanding Zero-Prefixed Numbers and Their Significance

In the realm of programming, numbers prefixed with zero can exhibit intriguing behavior. Let's delve into the specifics using examples from Visual Studio 2013.

Consider the following code snippet:

int i = 07;     // i == 7
int i = 16;     // i == 16
int i = 00016;  // i == 14, why?
int i = 05016;  // i == 2574, wow )
int i = 08;     // compile error, compiler expects octal number...

Special Treatment of Zero-Prefixed Numbers

The compiler interprets zero-prefixed numbers differently depending on the context:

  • Decimal Numbers (Base 10): When a zero-prefixed number consists only of digits from 0 to 7, it is interpreted as a decimal number. For example, 07 is equivalent to 7.
  • Octal Numbers (Base 8): If a zero-prefixed number contains a digit 8 or 9, it is considered an octal number. However, note that this is invalid usage according to the C standard.
  • Hexadecimal Numbers (Base 16): Zero-prefixed numbers that begin with 0x or 0X are interpreted as hexadecimal numbers.

Unusual Behavior with 00016 and 05016

The assignment int i = 00016; resolves to i == 14 because the compiler treats the leading zeros as extra octal digits, even though this is not valid according to the C standard.

Similarly, int i = 05016; yields i == 2574 because the compiler interprets it as follows:

  • 050 is treated as octal 50.
  • 16 is treated as decimal 16.
  • The result is computed as (50 * 8) 16 = 2574.

Compile Error with 08

An integer literal starting with 0 followed by a digit other than 0-7, such as 08, triggers a compile error because the compiler expects it to be an octal number, but 8 is not a valid octal digit.

The above is the detailed content of Why Do Zero-Prefixed Numbers Behave Unexpectedly in 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