Home >Backend Development >C++ >What\'s the Key Difference Between `%i` and `%d` Format Specifiers in C\'s `printf` and `scanf`?

What\'s the Key Difference Between `%i` and `%d` Format Specifiers in C\'s `printf` and `scanf`?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-12-03 00:44:09574browse

What's the Key Difference Between `%i` and `%d` Format Specifiers in C's `printf` and `scanf`?

Understanding the Difference Between Format Specifiers %i and %d

When utilizing formatted input/output functions like printf and scanf, the format specifiers play a crucial role in controlling the type of data to be printed or read. Among these, the specifiers %d (integer) and %i (integer) warrant careful consideration.

Usage in printf

For output operations, there is no functional difference between %d and %i. Both will output a signed decimal integer. For instance, using either %d or %i with the integer value 100 would result in the string "100".

Usage in scanf

However, the distinction between %d and %i becomes evident in input operations. While %d strictly scans a signed decimal integer, %i supports decimal, hexadecimal, and octal formats.

  • Decimal (default): Both %d and %i will accept a sequence of decimal digits (e.g., 123, -45).
  • Hexadecimal: %i allows input in hexadecimal format if prefixed with "0x" (e.g., 0x123). On the other hand, %d will treat "0x" as part of the integer string.
  • Octal: Similarly, %i supports octal input if prefixed with "0" (e.g., 033). In contrast, %d would interpret "033" as a decimal integer.

To illustrate the difference, consider the following example:

scanf("%i", &number);

If the user enters "033", %i will interpret it as an octal number and assign the value 27 to the variable 'number', whereas %d would assign 33.

The above is the detailed content of What\'s the Key Difference Between `%i` and `%d` Format Specifiers in C\'s `printf` and `scanf`?. 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