1

If I use wrong format specifier like this :

unsigned int i = -1;
printf("%d\n", i);

It is invoked undefined behaviour because %u format specifier for unsigned.

C11 standard ยง 7.21.6.1(P9):

If a conversion specification is invalid, the behavior is undefined.282) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.

But, If I write like this:

unsigned int i = -1;
printf("%d\n", (int)i); // unsigned to signed 

Is it also undefined behaviour?

msc
  • 33,420
  • 29
  • 119
  • 214
  • You probably miss some *language-lawyer* tag โ€“ Basile Starynkevitch Dec 12 '17 at 07:27
  • A signed integer can always be interpreted as an unsigned one, unless you have some exotic crap system with one's complement and trap representations. โ€“ Lundin Dec 12 '17 at 07:54
  • 2
    Reopened - the linked question was about signed to unsigned, whereas this is about unsigned to signed which is different. (and this has a good answer) โ€“ M.M Dec 12 '17 at 08:33

1 Answers1

6

Is it also undefined behavior?

No. The argument is of the correct type. It expects a signed integer, and you provide one. The only caveat is that the outcome is implementation defined (not undefined).

6.3.1.3 Signed and unsigned integers - p3

Otherwise, the new type is signed and the value cannot be represented in it; either the result is implementation-defined or an implementation-defined signal is raised.

So either it will print something (because the conversion happened), or will raise some signal. Whatever happens, your implementation is required to let you know by documenting it.

Eric Postpischil
  • 195,579
  • 13
  • 168
  • 312
StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458