0

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};
    
4
  • Which is your question? Commented Jul 29, 2022 at 10:00
  • @MarcoBeninca: Is it a mistake in the book? Commented Jul 29, 2022 at 10:01
  • Note that Stroustrup's books have plenty of typos. The errata only mention those he doesn't consider obvious. Commented Jul 29, 2022 at 10:27
  • how is scale defined? Commented Jul 29, 2022 at 10:58

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

compiler constexpr support isn't stable (they're chasing a moving target), so compiler bugs are not uncommon. Therefore while it's useful to know what a particular compiler thinks of a particular piece of code, you shouldn't accept it as absolute truth.
@BenVoigt Nothing is ever absolute. But I doubt there is still much happening with constexpr and c++11. The moving target is in support for c++20 and the STL.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.