What is the difference between "%i" and "%d" in the scanf function, are they same or different? In printf, "%d" is used to print an integer value, so is the use of "%i".
Difference between "%i" and "%d"
121 Views Asked by Haider Shah AtThere are 2 best solutions below
On
With printf, you always want to specify the base to print in. So %d prints in decimal, and %x prints in hexadecimal, and %o prints in octal (base 8).
The formats for scanf generally mirror printf. So %d reads decimal, and %x reads hexadecimal, and %o reads octal.
Now, in a C source file, you can use any of the three bases, with a prefix indicating your choice: a leading 0x indicates hexadecimal, and a leading 0 indicates octal. That's for the C compiler reading C source files, but somebody realized it'd be nice if your program had the ability to read input in any base at run time. So, for example, the strtol function is normally told (via its third argument) exactly what base to accept, but if you give it a third argument of 0, it intuits the base based on a prefix, just like the compiler does.
Now we get to %i. Someone decided it'd be nice to give scanf the ability to read any base, just like strtol does. So that's what %i does: it, well, reads any base, paying attention to a leading 0 or 0x prefix, just like strtol does.
But then, finally, since it's nice if printf and scanf formats mirror each other, someone decided it would be good if printf accepted %i also. In a way it's meaningless: you obviously can't intuit an output format the same way you can an input format. So for printf, %i always means decimal, just like %d. So it's redundant and unnecessary, but I've noticed that more and more of the questions asked here on SO seem to use it, so someone out there most be teaching new programmers to use it.
The format specification
%iopposite to the conversion specification%dused in the family of functions likescanfcan interpret the input as an octal number if it starts from0or as hexadecimal number if it is preceded by the hexadecimal suffix0xor0X.From the C Standard (7.21.6.2 The fscanf function)
and (7.22.1.4 The strtol, strtoll, strtoul, and strtoull functions)
And integer constants are