Unsigned. Use %u
. When performing default promotions on integral expressions (because of printf()
being a variadic function), unsigned to signed conversion does not happen.
printf format for difference of two unsigned ints
-
30-05-2022 - |
문제
In pure ANSI C (C89), I have the following.
unsigned y=<smallnumber>,x=y+3;
printf("%<whatgoeshere>\n",x-y);
What do I put after the %
to be absolutely sure it will print 3
? I can see arguments for both %u
(result is unsigned if both operands are) and %d
(integral expressions are converted to int
when passing arguments to printf
) here.
Of course both work on any reasonable compiler, which is exactly why I ask here. :-) I have a feeling only one is really correct accordung to standard (but even that could be wrong).
해결책
다른 팁
This way
printf( "%d\n", (int)(x-y) );
It works for x < y, unlike %u
.
Though it doesn't work if result of x-y
is out of range of signed int.
제휴하지 않습니다 StackOverflow