Difference between if constexpr() and if()
Features |
if constexpr() |
if() |
---|---|---|
Execution |
Compile-time, the code branch that is not satisfying the condition is discarded at compile time. |
Runtime, the code branch that is not satisfying the is not executed during runtime. |
Condition |
Condition must be a constant expressions |
Condition can be any expression |
Syntax Flexibility |
Compile-Time Conditions |
Runtime Conditions |
Branching |
Conditional code generation |
Multiple paths at runtime |
Error Reporting |
Early Errors, errors related to branch that is discarded are reported during compilation. |
Errors related to both discarded and non discarded branches may be reported during compilation and runtime. |
Constant evaluation |
Evaluated Immediately |
Evaluation may be deferred |
Performance |
Optimized Execution |
Runtime Overhead |
Compile-time checks |
Yes it checks at compile time |
No compile time checks |
if constexpr in C++ 17
In C++17, if constexpr
feature was introduced to allow compile-time branching based on constant expressions. Unlike regular if
statements, which are evaluated at runtime, the if constexpr allows the compiler to discard branches of code that do not apply. It means only the branch of code for which the condition is true is compiled and other code branch is discarded during compilation.