Namespaces
Variants
Actions

Constants and literals

From cppreference.com
Revision as of 23:43, 6 December 2013 by P12 (Talk | contribs)


Constants, by their simplest definition, are values that do not change. In C++, a constant is a variable with a fixed value defined before the program runs. A constant is treated as a regular variable with a single exception that its value can not be changed.

Contents

Literals

A literal is a way to express the value that might be assigned to a constant. Literals do not refer to variables, they are the values themselves. For example, consider the following expression:

const int z = 5;

Here z is a constant, whereas 5 is an integer literal. There are several types of literals in C++:

  • integer literals which define define integer values such as 0, 5 or -51984.
  • floating-point literals which define floating-point values such as 0.0, 0.5 or 3.141529.
  • boolean literals which define the boolean values true and false.
  • character literals which define single characters.
  • string literals which define character strings.

Each of these literal types have a distinct syntax rules. Deviating from these rules results in an error.

Integer literals

Floating-point literals

Boolean literals

Boolean literals represent boolean values. They are the simplest category of literals in that only two different values are allowed: true and false. Both of them evaluate to a value of type bool. bool may be converted to integer types, in which case a true yields to nonzero value, whereas false yields zero.

#include <iostream>
#include <iomanip>
 
int main()
{
    std::cout << std::boolalpha; // print booleans in readable form
 
    bool b = true;
    // print a bool constant
    std::cout << b << '\n';
    // print a literal directly
    std::cout << true << '\n';
    std::cout << false << '\n';
 
    int i = b;
    // print an integer representation of bool
    std::cout << i << '\n';
    i = false;
    std::cout << i << '\n';
}

Output:

true
false
1
0

Character literals

Character literals represent a single character.

String literals