Formatted IO with %i and %d: A Detailed Comparison
When utilizing formatted IO functions like printf and scanf, understanding the subtle differences between format specifiers is crucial. Two common specifiers, %d and %i, can lead to confusion if their distinct behaviors are not fully grasped.
Output: Identical Functionalities
If %i and %d are employed for output purposes (i.e., in printf), there is no noticeable difference between them. Both specifiers will produce the same output, whether it be decimal, hexadecimal, or octal.
Input: Where the Distinction Emerges
However, when using these specifiers for input (i.e., in scanf), a clear distinction arises. %d interprets input as an integer in signed decimal format. This means that numbers like -512 would be properly recognized and assigned negative values.
In contrast, %i defaults to decimal interpretation but exhibits a more flexible nature. It not only handles decimal integers but also accommodates hexadecimal and octal values when preceded by relevant prefixes. For instance, 0x1A would be interpreted as a hexadecimal number, while 023 would be recognized as octal.
Practical Example
Consider the input string "033". If scanf reads this using %d, it will treat it as the decimal integer 33. However, using %i, scanf recognizes the leading 0 as an octal prefix, resulting in the integer 27 being assigned to the variable.
Conclusion
In summary, while %i and %d perform similarly for output in formatted IO functions, they exhibit different behaviors for input. %d restricts input to signed decimal numbers, while %i offers more versatility by accommodating hexadecimal and octal values. Understanding this distinction is essential for accurate input handling in C programs.
The above is the detailed content of %i vs. %d in C\'s Formatted I/O: What\'s the Difference?. For more information, please follow other related articles on the PHP Chinese website!