why printf behaves differently when we try to print character as a float and as a hexadecimal?

后端 未结 5 1763
天命终不由人
天命终不由人 2021-01-29 12:41

I tried to print character as a float in printf and got output 0. What is the reason for this.
Also:

char c=\'z\';
printf(\"%f %X\",c,c);
5条回答
  •  离开以前
    2021-01-29 13:17

    The printf() function is a variadic function, which means that you can pass a variable number of arguments of unspecified types to it. This also means that the compiler doesn't know what type of arguments the function expects, and so it cannot convert the arguments to the correct types. (Modern compilers can warn you if you get the arguments wrong to printf, if you invoke it with enough warning flags.)

    For historical reasons, you can not pass an integer argument of smaller rank than int, or a floating type of smaller rank than double to a variadic function. A float will be converted to double and a char will be converted to int (or unsigned int on bizarre implementations) through a process called the default argument promotions.

    When printf parses its parameters (arguments are passed to a function, parameters are what the function receives), it retrieves them using whatever method is appropriate for the type specified by the format string. The "%f" specifier expects a double. The "%X" specifier expects an unsigned int.

    If you pass an int and printf tries to retrieve a double, you invoke undefined behaviour.
    If you pass an int and printf tries to retrieve an unsigned int, you invoke undefined behaviour.

    Undefined behaviour may include (but is not limited to) printing strange values, crashing your program or (the most insidious of them all) doing exactly what you expect.

    Source: n1570 (The final public draft of the current C standard)

提交回复
热议问题