Home > Backend Development > C++ > %i vs. %d in C: When Do These Format Specifiers Differ?

%i vs. %d in C: When Do These Format Specifiers Differ?

Patricia Arquette
Release: 2024-12-03 13:37:12
Original
370 people have browsed it

%i vs. %d in C: When Do These Format Specifiers Differ?

Differences Between Format Specifiers %i and %d in Formatted I/O Functions (printf / scanf)

Formatted I/O functions like printf and scanf utilize conversion specifiers to control how data is represented during input or output. Among these specifiers, %i and %d are commonly used for integers.

Usage for Output (%i vs. %d)

When used as format specifiers for output, there is no distinction between %i and %d. Both produce the same result. They represent an integer value in decimal format.

Input Specifiers

However, the distinction emerges when using %i and %d as input specifiers (in scanf). Here's where the key difference lies:

  • %d: Specifies a signed decimal integer. It expects the input to be a base-10 number (decimal).
  • %i: Default behavior is similar to %d (signed decimal integer). However, it has an additional feature: it allows input in other bases, such as:

    • Hexadecimal: Preceded by "0x", it interprets the input as a hexadecimal number.
    • Octal: Preceded by "0", it interprets the input as an octal number.

Practical Example

To illustrate the difference, consider the input string "033".

  • With %d: It treats it as a signed decimal integer, resulting in the value 33.
  • With %i: Since the input starts with "0", it recognizes it as an octal number. The value of "033" in octal is 27.

In summary, while %i and %d behave similarly for output, they differ in their behavior for input. %i provides extended functionality by allowing hexadecimal and octal input, while %d is strictly limited to signed decimal input.

The above is the detailed content of %i vs. %d in C: When Do These Format Specifiers Differ?. 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