What is constexpr?

What is the use for constexpr and how does it differentiate from const. It says something like it gets called during compile time or something like that but I don't even know what that meaans.
http://lmgtfy.com/?q=c%2B%2B+constexpr

Wasnt that hard was it?...
I don't know if it makes it any more clear but the site has a code sample:

http://en.cppreference.com/w/cpp/language/constexpr

-Alex
const just means you are not allowed to modify something. constexpr says more than that. It says that the value can be computed at compile time.

Example:

1
2
3
4
5
6
7
8
9
10
void foo(int i)
{
	// C is const so you are not allowed to change its value, but it can't be computed at 
	// compile time because it depends on the value of i so constexpr would not work here.
	const int C = 2 * i;
}

// The value of D can be computed at compile time 
// so you could use constexpr instead of const here.
const int D = 5 + 1; 


When specifying the size of an array with automatic storage duration, or when passing numerical template arguments the value has to be constexpr. A variable that is declared const can still be constexpr but by using a constexpr you can be sure the value really is a constexpr, or otherwise the compiler will give you an error.
Last edited on
Topic archived. No new replies allowed.