Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

constexpr and std::cout working on function but not in lambda

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
}
like image 302
João Paulo Avatar asked Jun 12 '19 18:06

João Paulo


2 Answers

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.

like image 176
Barry Avatar answered Oct 25 '22 18:10

Barry


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.

like image 44
Rakete1111 Avatar answered Oct 25 '22 17:10

Rakete1111