Cpp - Compile-Time Constant Expressions


Functions can use the const keyword to return a constant value.

const int getCentury() 
    return 100; 

Constant expressions is created with the constexpr keyword:

constexpr int getCentury() 
    return 100; 

The constant expression must have a non-void return type and return an expression as its contents.

The expression returned can contain only literal values, calls to other constant expressions or variables that have been defined with constexpr.

The following statements define a constant called century and a constant expression called year using the constexpr keyword:

const int century = 100; 
constexpr year = 2016 + century; 

The following code uses a constant expression to represent the value of PI.

And use it to calculate the area of a circle based on a radius value entered by the user.


#include <iostream>
// get an approximate value of PI 
constexpr double getPi() { 
    return (double) 22 / 7; 
int main() { //from  w  w  w .j a v a 2s .c o  m
    float radius; 
    std::cout << "Enter the radius of the circle: "; 
    std::cin >> radius; 
    // the area equals PI * the radius squared 
    double area = getPi() * (radius * radius); 
    std::cout << "\nCircle's area: " << area << std::endl; 
    return 0; 


Related Topic