c++ Advanced : constexpr

Amit.Kumar
1 min readJun 10, 2023

constexpr

#include <iostream>

constexpr int square(int x) {
return x * x;
}

int main() {
constexpr int size = 5;
constexpr int result = square(size);

std::cout << "Square of " << size << " is " << result << std::endl;

return 0;
}

In this code, we define a constexpr function called square() that takes an integer x as its argument and returns the square of x. The constexpr keyword indicates that this function can be evaluated at compile time.

Inside the main() function, we declare a constexpr variable size with a value of 5. We also declare another constexpr variable result and assign it the value returned by calling the square() function with size as the argument. Since both size and result are declared as constexpr, the compiler can compute their values during compilation.

Finally, we print the values of size and result using std::cout. Since size and result are known at compile time, the output will be "Square of 5 is 25".

--

--

Amit.Kumar

I have been a coder all my life . And yes a dreamer too. But i am also interested in understanding different aspects of life .