Home > front end >  Programming principles and practice using C error: constexpr
Programming principles and practice using C error: constexpr

Time:07-30

In Stroustrup's "Programming principles and practice" book, there's an example of constexpr like this:

void user(Point p1)
{
    Point p2 {10,10};
    Point p3 = scale(p1); // OK: p3 == {100,8}; run-time evaluation is fine
    constexpr Point p4 = scale(p2); // p4 == {100,8}
    constexpr Point p5 = scale(p1); // error: scale (p1) is not a constant
                                    // expression
    constexpr Point p6 = scale(p2); // p6 == {100,8}
    // . . .
}
  • But think he is mistaken: p2although initialized with constant expression arguments (literals here 10, 10) it is not a constexpr object because it is not declared so.

So normally p4 and p6 are in error here: (cannot use p2 in a constant expression). it is like p1.

  • To correct it:

     constexpr Point p2{10, 10};
    

CodePudding user response:

You know who is really good at telling you if something is allowed as a constexpr? Your compiler. https://godbolt.org/z/4Kdocx83v

And you are right, it's broken.

  • Related