Understanding implicit conversions for printf

前端 未结 2 1667
终归单人心
终归单人心 2021-01-25 04:44

The C99 Standard differentiate between implicit and explicit type conversions (6.3 Conversions). I guess, but could not found, that implicit casts are performed, when the target

相关标签:
2条回答
  • 2021-01-25 05:00

    Arguments to va_arg functions are not converted, syntactically the compiler knows nothing about the arguments for such functions, so he can't do that. Modern compilers do know to interpret the format string, though, and so they are able to warn you when something fishy is going on. That's what happening when you see the warning from gcc.

    To be more precise, there are some promotions that are done for narrow integer types, they are promoted to int, and for float which is promoted to double. But that is all magic that can happen, here.

    In summary, always use the correct format specifier.

    BTW, for size_t as of your sizeof expressions the correct one is %zu.

    0 讨论(0)
  • 2021-01-25 05:25
    printf("INT_MIN as double (or float?): %e\n", a);
    

    Above line has problem You can not use %e to print ints. The behavior is undefined.

    You should use

    printf("INT_MIN as double (or float?): %e\n", (double)a);
    

    or

    double t = a;
    printf("INT_MIN as double (or float?): %e\n", t);
    

    Related post: This post explains how using incorrect print specifiers in printf can lead to UB.

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