constexpr in c++ 11 is a new added feature. constexpr is short name of  constant expression. in c++ 11 it is possible to evaluate the value of the function or variable at compile time by using ‘constexpr’ specifier. Let us take a very simple example to understand the use of constexpr.

Let us try to compile to compile below code.

#include <iostream>
using namespace std;

int foo() {
	return 5;
}
int arr[5 + foo()]; // error

int main() {
	return 0;
}
Invoking: GCC C++ Compiler
g++  -std=c++11 -O0 -g3 -Wall -c -MMD -MP -MF"ex.d" -MT"11125.d" -o"ex.o" "../ex.cpp"
../ex.cpp:7:18: error: array bound is not an integer constant before ‘]’ token
 int arr[5 + foo()];
                  ^
make: *** [ex.o] Error 1

This error comes because compiler is unable to compute the return value of function foo at compile time. But we can declare function foo constexpr so that compiler can evaluate it at compile time. see below code.

#include <iostream>
using namespace std;

constexpr int foo() {
	return 5;
}
int arr[5 + foo()]; // ok

int main() {
	return 0;
}

A function declared with constexpr is also known as constant expression function. In the above example foo is a constant expression function.

Limitation of constexpr

  • A function with multiple return statement is not allowed to be constant expression function. So following code will not complie as foo has multiple return statement.
#include <iostream>
using namespace std;

class foo {
public:
	constexpr foo(){}
	constexpr int number(int a) {

		if( a > 2) return -1;
		else return 2;
	}
};

int main() {
	foo foo_obj;
	cout << foo_obj.number(5);
	return 0;
}
  • Function must have non-void return type. The below code will not compile because foo has non-void return type.
#include <iostream>
using namespace std;

constexpr void foo() {
	return;
}

int main() {
	return 0;
}
  • The function body cannot declare variables or define new types.
#include <iostream>
using namespace std;

constexpr int foo(int a) {
	int b = 0;
	return a;
}

int main() {
	return 0;
}
//  error cannot compile

constexpr constructor

A constexpr constructor allows the compiler to initialize the object at compile-time if the constructor’s arguments are all constant expressions.

#include <iostream>
using namespace std;

class foo {
public:
	constexpr foo(){} // constant expression constructor
	constexpr int number(int a) { return a;}
};

int main() {
	foo foo_obj;
	cout << foo_obj.number(5);
	return 0;
}

Ref:

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



Related Contents to follow