The following code produces an error with gcc in the latest versions:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
constexpr double d = 2.2;
constexpr int i = d*10;
printf("%d\n", i);
return EXIT_SUCCESS;
}
<source>:8:23: error: 'constexpr' integer initializer is not an integer constant expression
7 | constexpr int i = d*10;
| ^
Casting the product defining i with (int)(d*10) won't work in gcc, but will work with the latest version of clang.
But we can do this with no problem:
#include<stdio.h>
#include<stdlib.h>
int main(void)
{
constexpr double d = 2.2;
constexpr double temp = d*10;
constexpr int i = (int)temp;
printf("%d\n", i);
return EXIT_SUCCESS;
}
Here's a Godbolt link.
I understand that constexpr floating point computations have some extra complexity and difficulties, based on rounding choice and the current environment, but it seems strange to allow the later and not the former. In the later, the temp value is usable but has to be placed in memory somewhere unnecessarily.
I wonder if I'm missing anything, or if this is just a limitation of the current C23 implementation.
Update: Thanks to Eric Postpischil for the correction that the latest version of clang does allow the first version as well, with the cast.
d*10might not equal 22.0.