Difference between %d and %i format specifier in C language
A format specifier is a sequence formed by an initial percentage sign (%) indicates a format specifier, which is used to specify the type and format of the data to be retrieved from the stream and stored into the locations pointed by the additional arguments. In short it tell us which type of data to store and which type of data to print.
For example – If we want to read and print integer using scanf() and printf() function, either %i or %d is used but there is subtle difference in both %i and %d format specifier.
%d specifies signed decimal integer while %i specifies integer.
%d and %i behave similar with printf
There is no difference between the %i and %d format specifiers for printf. Consider a following example.
Output: Value of num using %d is = 9 Value of num using %i is = 9
%d and %i behavior is different in scanf
%d assume base 10 while %i auto detects the base. Therefore, both specifiers behaves differently while they are used with an input specifier. So, 012 would be 10 with %i but 12 with %d.
- %d takes integer value as signed decimal integer i.e. it takes negative values along with positive values but values should be in decimal otherwise it will print garbage value.( Note: if input is in octal format like:012 then %d will ignore 0 and take input as 12) Consider a following example.
- %i takes integer value as integer value with decimal, hexadecimal or octal type.
To enter a value in hexadecimal format – value should be provided by preceding “0x” and value in octal format – value should be provided by preceding “0”.
Consider the following example.
Output: Enter value of a in decimal format:12 Enter value of b in octal format: 012 Enter value of c in hexadecimal format: 0x12 a = 12, b = 10, c = 18
The decimal value of a as 12 is 12
The decimal value of b as 12(octal) is 10
The decimal value of c as 12(hexadecimal) is 18
This article is contributed by Shubham Bansal. If you like GeeksforGeeks and would like to contribute, you can also write an article using write.geeksforgeeks.org or mail your article to email@example.com. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Login to comment...