Why constexpr
does not work with std::cout
, but works with printf
?
#include <iostream>
constexpr void f() { std::cout << ""; } //error
constexpr void g() { printf(""); } //ok
And why std::cout
works with lambdas constexpr
?
#include <iostream>
int main () {
auto h = []() constexpr { std::cout << ""; }; //ok
}
Technically, it doesn't work with any of them.
From [dcl.constexr]:
For a constexpr function or constexpr constructor that is neither defaulted nor a template, if no argument values exist such that an invocation of the function or constructor could be an evaluated subexpression of a core constant expression, or, for a constructor, a constant initializer for some object ([basic.start.static]), the program is ill-formed, no diagnostic required.
f()
and g()
are never constant expressions (neither std::cout << x
nor printf()
are constexpr functions), so the constexpr
declaration is ill-formed. But the compiler isn't required to diagnose this (in this case, it may be easy, but in the general case... not so much). What you're seeing is that your compiler was able to diagnose one problem but not the other.
But they're both wrong.
It doesn't. You need to use it to force a compile time error.
constexpr int a = f(), 0; // fails
constexpr int b = g(), 0; // fails
constexpr
functions that never produce a constant expression are ill-formed; no diagnostic required. This means that compilers do a best effort check to see if that is the case, but your program already has an error either way. Seems like gcc can't see that printf
is not a constant expression. clang errors at the definition.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With