- Examples
In this lesson, we’ll take a look at the examples of implementing constexpr functions.
We'll cover the following...
Example 1
Press + to interact
//C++ 11// constExpression.cpp#include <iostream>constexpr int square(int x) { return x * x; }constexpr int squareToSquare(int x){ return square(square(x));}int main() {std::cout << std::endl;int a = 10;static_assert(square(a) == 100, "you calculated it wrong");static_assert(squareToSquare(10) == 10000 , "you calculated it wrong");std::cout<< "square(10)= " << square(10) << std::endl;std::cout<< "squareToSquare(10)= " << squareToSquare(10) << std::endl;constexpr int constExpr= square(10);int arrayClassic[100];int arrayNewWithConstExpression[constExpr];int arrayNewWithConstExpressioFunction[square(10)];std::cout << std::endl;}
Explanation
-
In the example above, we implemented two
constexpr
functions for C++11:constexpr int square(int x)
...
Access this course and 1400+ top-rated courses and projects.