...
Subclause 6.8.6.4, paragraph 23, of the C Standard [ISO/IEC 9899:2011] states:
...
Function f
is allowed to return a value wider than float
, but function g
(which uses the wider constant) is not.
Although the current text standard does not require narrowing return expressions of the same type as the function, it does not clearly state what is allowed. Is it allowed to narrow the result? Is it allowed to narrow the result sometimes but not always? Is it allowed to partially narrow the result (for example, if the application binary interface [ABI] returns floats in double format, but a float function has a float return expression evaluated to wider than double)? An aggressive implementation could argue yes to all these questions, though the resulting behavior would complicate debugging and error analysis.
Footnote 160 says a cast may be used to remove extra range and precision from the return expression. This means that a predictable program must have casts on all floating-point function calls (except where the function directly feeds an operator-like assignment that implies the conversion). With type-generic math (tgmath.h)
, the programmer has to reason through the tgmath.h
resolution rules to determine which casts to apply. These are significant obstacles to writing predictable code.
Note that WG14 voted to include the following text in the C Standard The C Standard, subclause F.6 states: [ISO/IEC 9899:2011]. It impacts only implementations that implement the optional Annex F, "IEC 60559 Floating-Point Arithmetic."
Require return expressions to be converted as if by assignment to the type of the function, but only in Annex F. This is a compromise that addresses the problems for Annex F implementations while not impacting non-Annex F implementations that exercise the license for wide returns.
Insert the following new subclause after F.5 (and increment subsequent subclause numbers):
F.6 The return statement
If the return expression is evaluated in a floating-point format different from the return type, then the expression is converted as if by assignment362 to the return type of the function and the resulting value is returned to the caller.
362) Assignment removes any extra range and precision.
It impacts only implementations that implement the optional Annex F, "IEC 60559 Floating-Point Arithmetic." The macro __STDC_IEC_559__
can be used to determine whether an implementation conforms to Annex F.
Noncompliant Code Example
...
This compliant solution casts the value of the expression in the return statement. It forces the return value to have the expected range and precision, as described in subclause 5.2.4.2.2, paragraph 89, of the C Standard [ISO/IEC 9899:2011].
...
[ISO/IEC 9899:2011] | Subclause 6.8.6.4, "The return Statement"Annex F.6, "IEC 60559 Floating-Point ArithmeticThe return statement" |
[WG14/N1396] |
...