Can someone clarify what the difference is between a constexpr (e.g. constexpr int WORD_LENGTH = 5) versus just creating a variable (e.g int WORD_LENGTH = 5)? Maybe it doesn’t matter at this point or it is explained later but if I remove the “constexpr” and leave “int WORD_LENGTH = 5” the code compiles without error. Just hoping for more insight on this. I’m not stuck.
Note the difference in Line 9 of the examples below:
Still don’t really get it. Using const keyword to prevent changes on the variable… ok… but an int or float is evaluated at compile time as well, isn’t it?
The value is evaluated at compile time. What you’re talking about is static typing. For an example of constexpr I have used Compile Explorer which shows you the generated assembly on the right. The following is with GCC 6.3 and with no optimisations.
Now the general principle of assembly, lesss is better. Though here you can see that in the constexpr version the function and function call (lines 1-8 +14) have disappeared and replaced with line 4
I think more importantly would be, what is the difference between const and constexpr?
Both would be constant, so why the need for a constant expression?
constexpr means the value can be evaluated at compile time and all uses will just be replaced by that value if it; look at the above example that demonstrates that.
Also constexpr means it’s probably also const though there’s cases where that’s not necessarily true.
As a horrible beginner in C++ and Assmbler, I just dont understand it (considering we are only in Section 2 atm).
I had a look at the Compile Explorer, which is a real neat tool. I understand that const and constexpr ensure the compiler evaluates and then replaces all references with the value, meaning no need to call the function since its…well…constant.
I looked around on stack overflow and all the answers are definitely over my head in terms of current knowledge of the language and terminology. Looking up, i’m not the only one that has an issue with grasping the concept.
A const would also be evaluated at compile time, no?