How # flag in printf works?

后端 未结 3 594
囚心锁ツ
囚心锁ツ 2021-01-28 16:03
#include 
int main()
{
  float x;
  x=(int)(float)(double)(5.5);
  printf(\"%#u\",x);
  return 0;
}

How the # flag in the p

相关标签:
3条回答
  • 2021-01-28 16:07

    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.

    0 讨论(0)
  • 2021-01-28 16:13

    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.

    0 讨论(0)
  • 2021-01-28 16:20

    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)

    0 讨论(0)
提交回复
热议问题