Home > Article > Backend Development > Do Variadic Functions in C and C Automatically Promote Floats to Doubles?
Float Promotion in Variadic Functions
Variadic functions allow for passing a variable number of arguments of different types. In C and C , a peculiar behavior occurs when attempting to pass a float argument to a variadic function like printf(). Contrary to intuition, the float is promoted to a double before being received by the function.
Do Variadic Functions Auto-Promote Floats?
Yes, variadic functions in C and C automatically promote float arguments to double. This behavior is defined in the language standards:
C99 (draft):
Arguments that have type float are promoted to double. These are called the default argument promotions.
C (draft):
A floating point type that is subject to the floating point promotion, the value of the argument is converted to the promoted type before the call.
This promotion is retained for compatibility with historical versions of C. Despite the potential drawbacks, it remains a default behavior in C99 and C .
Implication for printf()
In the case of printf(), the phenomenon arises because printf() expects format specifiers and arguments to match. Since the format specifiers for doubles and floats are different, the float argument is promoted to a double to meet the requirements of the function. This ensures compatibility and simplifies the handling of floating-point arguments.
The above is the detailed content of Do Variadic Functions in C and C Automatically Promote Floats to Doubles?. For more information, please follow other related articles on the PHP Chinese website!