Why exactly do we use "constexpr" for the word length variable?

The coding knowledge I know consists only of Java (through a high school course taken this past school year), where we would have just put “int” without anything like “constexpr”. So, I’m pretty confused as to why we need to add “constexpr int” rather than just “int” here in C++. Does the reason have to do with the way we’re using this particular variable, or is this just how it’s done in C++?

constexpr was added in C++ 11 and is similar to const but can be applied to more expressions. In the lecture Ben is basically saying we don’t want to modify WORD_LENGTH anywhere in the code, and he’s using the C++ 11 keyword for the definition. Check out the msdn article here for more info.

So, if I’m understanding this correctly, constexpr will give an error if the variable is modified anywhere in the code?

That’s correct! You would see the following compile-time error:

Error C3892 'WORLD_LENGTH': you cannot assign to a variable that is const

1 Like

Okay, thank you!

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.

Privacy & Terms