Вопрос

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