How # flag in printf works?

2020-05-01 09:28发布

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

标签: c printf
3条回答
Luminary・发光体
2楼-- · 2020-05-01 10:01

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.

查看更多
家丑人穷心不美
3楼-- · 2020-05-01 10:03

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.

查看更多
相关推荐>>
4楼-- · 2020-05-01 10:13

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)

查看更多
登录 后发表回答