sabakioukenasai
sabakioukenasai

Reputation: 11

Unexpected output of printf("%0x", aFloat) in C

I have a question that puzzles me,code below will print -2.

float f = -123.456;
printf("%0x", f);

and the compiler issued a warning:

format specifies type 'unsigned int' but the argument has type 'float'

I'm just wondering how can '-123.456' be interpreted as '-2'

Upvotes: 1

Views: 57

Answers (1)

Yunnosch
Yunnosch

Reputation: 26703

The warning tells you that the format specifier which you chose, "%0x" is only for unsigned int, but that in contrast to that what you provide is a something else, a float.
The result is meaningless, which is what you observe.
Read up on printf() and pick a format specifier which matches float and does what you try.

E.g. https://en.cppreference.com/w/c/io/fprintf specifies:

If any argument ... is not the type expected by the corresponding conversion specifier... the behavior is undefined.

That is the formal phrasing for "meaningless". So much so that even guessing why you get -2 or trying to predict whether the code behaves the same elsewhere or even in the same enviroment is already meaningless; "undefined behaviour" is the term to look up for that scope.

Upvotes: 3

Related Questions