%i or %d to print integer in C using printf()?

Dummy Code picture Dummy Code · Jun 26, 2013 · Viewed 191.3k times · Source

I am just learning C and I have a little knowledge of Objective-C due to dabbling in iOS development, however, in Objective-C I was using NSLog(@"%i", x); to print the variable x to the console however I have been reading a few C tutorials and they are saying to use %d instead of %i.

printf("%d", x); and printf("%i", x); both print x to the console correctly.

These both seem to get me to the same place so I am asking the experienced developers which is preferred? Is one more semantically correct or is right?

Answer

user529758 picture user529758 · Jun 26, 2013

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.)