Consider the following code:
#include <stdio.h>
constexpr int f()
{
return printf("a side effect!\n");
}
int main()
{
char a[f()];
printf("%zd\n", sizeof a);
}
I would have expected the compiler to complain about the call to printf
inside f
, because f
is supposed to be constexpr
, but printf
is not. Why does the program compile and print 15?
The program is ill-formed and requires no diagnostic according to the C++11 draft standard section
7.1.5
The constexpr specifier paragraph 5 which says:and provides the following example:
and section
5.19
paragraph 2 says:and includes:
We would probably prefer a diagnostic in this case, it could just be an oversight, I have a bug report for a similar situation where
gcc
does not produce an error but we would probably like it to: Is the compiler allowed leeway in what it considers undefined behavior in a constant expression?.Update
Using the
-fno-builtin
flag will causegcc
to generate the following error:So
gcc
does consider this ill-formed it is just ignores it when it is using the builtin version ofprintf
.Although somewhat inconsistently using the
-pedantic
produces the following warning:Note that using
f()
to initialized a constexpr variable:does generate an error:
Note that additionally in the more general case a compiler is not allowed mark standard library functions as constexpr unless explicitly allowed by the standard.