Hmm, ok, I can see that my previous answer is not particularly clear, sorry.
Let me try again:
Yes, you can declare MAX_TRY_NBR in the same file as the rest of your code. It’s as simple as moving the declaration from your .h file to the top of your .cpp file. If you are positive that you won’t be using the same const in other files, go for it! But if you need access to the MAX_TRY_NBR in other files / classes you have two options:
- Copy the MAX_TRY_NBR declaration into every .cpp file where you need it (don’t do that, prone to errors and misery)
- write a .h file with MAX_TRY_NBR once and
#include it everywhere you need it
I found this explanation for const Vs constexpr and I think it’s quite good and hands-on with an example: https://forums.unrealengine.com/development-discussion/c-gameplay-programming/29426-const-vs-constexpr
The important difference, as you said yourself, is constexpr is evaluated at compile-time whereas const is evaluated at run-time.
compile-time = when the compiler creates the binary
run-time = when the binary is executed
With compile-time evaluation, the resulting binary will not contain any logic, just a number (or string or whatever). That’s the most optimised thing you can get (only works this way if you use the “Release” build option, if you use debug, there is no difference in the binary between constexpr and const, I actually had a look at the assembly output to find that out).
With run-time evaluation, the binary will contain logic and your const statement will be executed, but it can only be executed once for a variable declaration, otherwise you get an error.
int constexpr ONE = 1;
std::cout << "ONE: " << ONE << std::endl;
// we can do maths with constants, as long as they can be evaluated at compile time
int constexpr FIVE = (400 / 8) / 10;
std::cout << "FIVE: " << FIVE << std::endl;
// we don't know at compile time what the user will type,
// this can be different every time you start the program
std::string UserInput = "";
std::cout << "Type something that will then be set to the constant INPUT_ONCE: ";
// side note: we have to use a variable that can be changed for getline() to work,
// that's why we don't set INPUT_ONCE directly
// although we don't know which value will be in INPUT_ONCE,
// we know that it won't change during the program's running time
// because we set it to const
std::string const INPUT_ONCE = UserInput; // try changing this to constexpr
std::cout << "INPUT_ONCE :" << INPUT_ONCE << std::endl;
I hope this time my answer is clearer.
Also, thanks for asking this question, you made me look into the difference of const vs constexpr quite thoroughly