Is there a difference between the following definitions?
const double PI = 3.141592653589793;
constexpr double PI = 3.141592653589793;
If not, which style is preferred in C++11?
Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.
Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.
Lost your password? Please enter your email address. You will receive a link and will create a new password via email.
Please briefly explain why you feel this question should be reported.
Please briefly explain why you feel this answer should be reported.
Please briefly explain why you feel this user should be reported.
I believe there is a difference. Let’s rename them so that we can talk about them more easily:
Both
PI1andPI2are constant, meaning you can not modify them. However onlyPI2is a compile-time constant. It shall be initialized at compile time.PI1may be initialized at compile time or run time. Furthermore, onlyPI2can be used in a context that requires a compile-time constant. For example:but:
and:
but:
As to which you should use? Use whichever meets your needs. Do you want to ensure that you have a compile time constant that can be used in contexts where a compile-time constant is required? Do you want to be able to initialize it with a computation done at run time? Etc.