The importance of compile time functions?

What is the importance of evaluating things at compile time?

 
int x = 10;


and

 
constexpr int x = 10;


Both of these are going to give us an integer data type with the value of 10. But the second example will be evaluated at compile time. Maybe I don't understand what "compile time" is, aside from it being what happens when the program compiles, so I'm kind of curious here.

What exactly is the importance of using compile time functions, and variables, in this case, constexpr? Why should one care about it? Is it purely performance? If so, how?

It wouldn't have any effect on the end user when the product ships would it?
Last edited on
It allows you to use it in places where a compile time constant is required.

To specify the size of an array.
1
2
constexpr int sz = 10;
int arr[sz]; // array of sz integers 

To use it as a template argument.
1
2
constexpr int number_of_bits = 81;
std::bitset<number_of_bits> bits;

To use it as a case label in a switch statement (often enums are used for this purpose).
1
2
3
4
5
6
7
8
constexpr int bad_num = 0;
switch (value)
{
case bad_num: 
	std::cout << "the value is bad\n"
default:
	std::cout << "the value is fine\n"
}

To use it in static_assert.
1
2
constexpr int required_int_size = 4;
static_assert(sizeof(int) < required_int_size, "int is too small on your platform");

To be able to use it with constexpr if.
1
2
3
4
5
6
constexpr bool debug_mode = true;
if constexpr (debug_mode)
{
	// this code will be ignored if debug_mode is set to false
	std::clog << "value of x is " << x << '\n';
}
Last edited on
Topic archived. No new replies allowed.