0

Do modern optimizing C++ compilers benefit from static_asserts?

For instance, if I assert an integer can only be in a restricted range, do compilers carry that information through the optimization steps or is it still just an integer?

Please do not answer that compilers could take it into account. The question is about whether or not current compilers do it.

7
  • 6
    isnt it the case that a static assert can only assert things that the compiler knows anyhow? I mean if the static assert fails then it fails at compile time, once it compiles there is no need for the assert anymore. Commented Jan 18, 2018 at 12:11
  • 3
    It doesn’t. It does, however, help debugging humans. Commented Jan 18, 2018 at 12:12
  • You can use __builtin_unreachable to do that. Commented Jan 18, 2018 at 12:17
  • @tobi in theory it is something knowable, as the compiler must check it, but knowable and known differ by an exponential gulf (or worse). In theory a proof engine in a compiler could be guided to new useful truths by one or more static asserts. Commented Jan 18, 2018 at 12:55
  • @Yakk yes, I am really not sure at all, hence I wrote the answer and hoped to get critisized. In general my feeling is that the compiler would be better at statically asserting stuff than I am Commented Jan 18, 2018 at 12:58

1 Answer 1

1

No, a static assert does not add additional opportunities for the compiler to perform optimizations. The reason is that a static assert can only test conditions that the compiler anyhow is aware of (how else could it evaluate the assert?). Also, the static assert can only fail at compile time, once it compiles there is no need for the static assert anymore. In this sense, the condition you used for the assert is certainly used by the compiler for optimizations, but the fact that you assert on that condition is no additional information for the compiler.

Disclaimer: This is what I conclude from my limited knowledge. I'd be happy to read a more sophisticated answer.

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.