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

有帮助吗?

解决方案

Unsigned. Use %u. When performing default promotions on integral expressions (because of printf() being a variadic function), unsigned to signed conversion does not happen.

其他提示

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.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top