#include <stdio.h>
int main()
{
float x;
x=(int)(float)(double)(5.5);
printf("%#u",x);
return 0;
}
How the #
flag in the printf is working here?
Everytime I run this code I get different(garbage) values.
I know that the #
flag works only with o , 0x, 0X, e, E, f, g, G
but when it is not defined for integers.
So is this an Undefined behaviour? I am getting correct values when I am using the above flags.
So tell me whether I am right or wrong.
From c11 standard.
7.21.6.1. p6:
#:
The result is converted to an ‘‘alternative form’’. For o conversion, it increases
the precision, if and only if necessary, to force the first digit of the result to be a
zero (if the value and precision are both 0, a single 0 is printed). For x (or X)
conversion, a nonzero result has 0x (or 0X) prefixed to it. For a, A, e, E, f, F, g,
and G conversions, the result of converting a floating-point number always
contains a decimal-point character, even if no digits follow it. (Normally, a
decimal-point character appears in the result of these conversions only if a digit
follows it.) For g and G conversions, trailing zeros are not removed from the
result. For other conversions, the behavior is undefined.
So, to clarify, using #
with u
is undefined.
From the manual page:
#
The value should be converted to an "alternate form" [...] For other conversions, the result is undefined.
So yes, it's undefined.
Using this flag with any other than the listed conversions is undefined behaviour. Don't use it with other conversions.
The value should be converted to an "alternate form".
For o conversions, the first character of the output string is made zero (by prefixing a 0 if it was not zero already).
For x and X conversions, a nonzero result has the string "0x" (or "0X" for X conversions) prepended to it.
For a, A, e, E, f, F, g, and G conversions, the result will always contain a decimal point, even if no digits follow it (normally, a decimal point appears in the results of those conversions only if a digit follows).
For g and G conversions, trailing zeros are not removed from the result as they would otherwise be.
For other conversions, the result is undefined.
(taken from the printf(3)-manpage. Wording is essentially the same as in the standard. Emphasis mine)