What is constexpr?

Apr 2, 2015 at 4:48pm
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.
Apr 2, 2015 at 4:48pm
http://lmgtfy.com/?q=c%2B%2B+constexpr

Wasnt that hard was it?...
Apr 2, 2015 at 4:57pm
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
Apr 2, 2015 at 5:15pm
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 Apr 2, 2015 at 5:19pm
Topic archived. No new replies allowed.