Constants in C++

Our first example demonstrates how to work with constants, character, string, boolean, and numeric values.

#include <iostream>
#include <cmath>

const std::string s = "constant";

int main() {
    std::cout << s << std::endl;

    const int n = 500000000;
    const double d = 3e20 / n;
    std::cout << d << std::endl;

    std::cout << static_cast<int64_t>(d) << std::endl;

    std::cout << sin(n) << std::endl;

    return 0;
}

To run this program, compile the code and then execute the binary.

$ g++ -o constants constants.cpp
$ ./constants
constant
6e+11
600000000000
-0.28470407323754404

This example covers the basics of using constants in C++. Constants can be declared using the const keyword. Arithmetic with constants is performed with arbitrary precision, and a numeric constant has no type until it is given one, such as by an explicit conversion. The last part demonstrates how to use a number in a context that requires a specific type, for example, in a function call to sin which expects a double.