When to use const and when to use constexpr? What's the difference between them?
Announcement
Collapse
No announcement yet.
const vs constexpr.
Collapse
X
-
I believe constexpr is initialized during compile time, so it can be used in situations where a compile time constant is needed. Const can be initialized during compile time or runtime.
http://stackoverflow.com/questions/1...r-on-variables
http://stackoverflow.com/questions/1...expr-and-const
-
A good way to figure that out is to try to set a static array's size using a variable declared as const or constexpr. A const is a constant expression provided that it is initialized with a constant expression, an integer literal for instance. The problem with const is that it can be initialized at run-time and won't warn you if you assign it to any function that isn't a constant expression, what I mean by that is
Code:const int i = ceil(1024); int Array[i] = {1,2,2,3,3,4,4};
Code:template<typename T> constexpr T Max(T a, T b) { return a < b ? b : a; } int main() { int a = 1, b = 2; Max(a, b); }
Code:template<typename T> constexpr T Max(T a, T b) { return a < b ? b : a; } int main() { int a = 1, b = 2; Max(1,2); }
Comment
Comment