%i means parse it as an integer in any base (octal, hexadecimal, or decimal, as indicated by a 0 or 0x prefix), while %d means parse it as a decimal integer.
In C programming language, %d and %i are format specifiers as where %d specifies the type of variable as decimal and %i specifies the type as integer. In usage terms, there is no difference in printf() function output while printing a number using %d or %i but using scanf the difference occurs.
printf("Enter an integer: "); scanf("%d", &number); Finally, the value stored in number is displayed on the screen using printf() . printf("You entered: %d", number);
They are completely equivalent when used with printf()
. Personally, I prefer %d
, it's used more often (should I say "it's the idiomatic conversion specifier for int
"?).
(One difference between %i
and %d
is that when used with scanf()
, then %d
always expects a decimal integer, whereas %i
recognizes the 0
and 0x
prefixes as octal and hexadecimal, but no sane programmer uses scanf()
anyway so this should not be a concern.)
I am just adding example here because I think examples make it easier to understand.
In printf() they behave identically so you can use any either %d or %i. But they behave differently in scanf().
For example:
int main()
{
int num,num2;
scanf("%d%i",&num,&num2);// reading num using %d and num2 using %i
printf("%d\t%d",num,num2);
return 0;
}
Output:
You can see the different results for identical inputs.
num
:
We are reading num
using %d
so when we enter 010
it ignores the first 0
and treats it as decimal 10
.
num2
:
We are reading num2
using %i
.
That means it will treat decimals, octals, and hexadecimals differently.
When it give num2
010
it sees the leading 0
and parses it as octal.
When we print it using %d
it prints the decimal equivalent of octal 010
which is 8
.
d
and i
conversion specifiers behave the same with fprintf
but behave differently for fscanf
.
As some other wrote in their answer, the idiomatic way to print an int
is using d
conversion specifier.
Regarding i
specifier and fprintf
, C99 Rationale says that:
The %i conversion specifier was added in C89 for programmer convenience to provide symmetry with fscanf’s %i conversion specifier, even though it has exactly the same meaning as the %d conversion specifier when used with fprintf.
%d seems to be the norm for printing integers, I never figured out why, they behave identically.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With