Home > Backend Development > C++ > What\'s the Key Difference Between `%i` and `%d` in C\'s Formatted Input/Output Functions?

What\'s the Key Difference Between `%i` and `%d` in C\'s Formatted Input/Output Functions?

Mary-Kate Olsen
Release: 2024-12-18 13:45:16
Original
540 people have browsed it

What's the Key Difference Between `%i` and `%d` in C's Formatted Input/Output Functions?

Understanding the Nuances of Conversion Specifiers: %i vs. %d in Formatted IO Functions

In the realm of formatted input/output (IO) functions like printf and scanf, conversion specifiers play a pivotal role in guiding the format of input or output. Among these specifiers, %i and %d often raise questions about their similarities and differences.

Output: A Uniform Presence

When used for output operations, such as with printf, both %i and %d behave identically. They consistently represent integers in decimal format. For instance, the following code snippet demonstrates their identical output:

int num = 123;
printf("Decimal representation (%%d): %d\n", num);
printf("Decimal representation (%%i): %i\n", num);
Copy after login

Input: Distinctive Behaviors

However, when deployed in input operations with scanf or similar functions, %i and %d exhibit marked differences. %d exclusively scans integers as signed decimal numbers. In contrast, %i retains its decimal interpretation but also embraces hexadecimal (prefixed with 0x) and octal (prefixed with 0) inputs.

To illustrate this distinction, consider the following example:

int num;
scanf("%%d", &num); // Only accepts decimal input
scanf("%%i", &num); // Accepts decimal, hexadecimal, or octal input
Copy after login

If the user enters 033, scanf will interpret it as 27 with %i (since it treats it as octal) and 33 with %d (strictly decimal).

In Summary...

While %i and %d share similar purposes in formatted IO, their distinction lies in their behavior during input operations. %d is confined to signed decimal input, whereas %i seamlessly handles both decimal and other base formats (hexadecimal and octal). This understanding is crucial for tailoring input operations to the specific needs of your program.

The above is the detailed content of What\'s the Key Difference Between `%i` and `%d` in C\'s Formatted Input/Output Functions?. 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