0

I am wondering why are the benefits of constexpr not optimized away by the compiler?

The compiler should be able to deduce that a value is known at compile time much better than a human (for example if all inputs to a function call are known), and then it should be able to mark that value as known for subsequent analysis until it becomes ambiguous. So why is it that we have to manually tell the compiler when that is the case (instead of just using the const keyword and leaving it to the compiler to evaluate the value at compile time).

Is this because the compiler technology is not yet capable of doing this or is there some sort of inherent limitation that prevents the compiler to do so?

7
  • 2
    All inputs to a function call being known is not a guarantee against other calls of the same function passing values determined at runtime. The compiler generates code based on what you tell it. Commented Jan 7, 2019 at 4:41
  • 3
    constexpr was not added to facilitate optimizations. A compiler doesn't have to optimize based upon it (even though it can and does). Commented Jan 7, 2019 at 5:02
  • 1
    @pooya13, The compiler has to generate code based on the information it has. If it doesn't know that all calls of a function are going to have compile-time constant parameters, how can it generate code making that assumption ? That's why you tell it - effectively preventing calls from passing values generated at runtime. Commented Jan 7, 2019 at 5:56
  • 1
    Compiler can check that programmer assumption is correct. adding an "innocent" debug print in a function would break constexpr for example. Commented Jan 7, 2019 at 8:10
  • 1
    Thank you @SidS and Jarod42. I was not thinking about compiler helping you clarify your intention when I was learning about this and incorrectly thought this was for code optimization. (I had missed your comments) Commented Sep 5, 2023 at 7:29

1 Answer 1

2

If you omit constexpr the compiler may well be able to still compute the value at compile time.

The main idea is that you can tell the compiler that you want something evaluated at compile time so that the compiler can emit an error when you make a mistake and use something that it isn't able to evaluate at compile time.

It obviously also allows use of the values in places where you are only allowed to use compile time constants like array sizes.

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.