I found questions about %i and %d on here, but all of them seemed to claim that they were the same in printf.
Compiler: Apple clang version 12.0.5 (clang-1205.0.22.9)
Note: 15 is 017 in octal and 0xf in hexidecimal.
I was previously under the impression that %d and %i only differed when used during scanf and not printf. Is this implementation defined behavior? Additionally I thought the number would have been converted and stored prior to the call to scanf.
Output: scanf using %i: 017 017 0xf 0xf //user input %i: 15, %d: 15, %i: 15, %d: 15 scanf using %d: 010 010 0xf 0xf //user input %i: 10, %d: 10, %i: 0, %d: 15 //They all make sense to me except these last two
Code:
int a, b, c, d;
printf("scanf using %%i: ");
scanf("%i %i %i %i", &a, &b, &c, &d);
printf("%%i: %i, %%d: %d, %%i: %i, %%d: %d\n\n",a,b,c,d);
printf("scanf using %%d: ");
scanf("%d %d %d %d", &a, &b, &c, &d);
printf("%%i: %i, %%d: %d, %%i: %i, %%d: %d\n\n",a,b,c,d);
scanf
returns. Also read more about the differences between%i
and%d
inscanf
(they do not work the same).0xf
is interpreted by%d
as0
, and thex
is not valid as part of a decimal integer, soscanf()
fails to read a fourth value and reports that it read just 3 values. It does not modify the fourth variable, so it continues to store what was in it before the call.