Namespaces
Variants
Actions

Constants and literals

From cppreference.com


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

  • base 10 integer literals: -1979, 0, +15
  • base 8 integer literals: 0775, -0123
  • base 16 integer literals: 0x775, 0XFF, 0Xd3b5

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.

Special characters that can not be expressed directly in source code, such as the newline, can be represented using escape characters, such as '\n' (a newline) or '\t' (a tab).

String literals

Characters enclosed by " and ", eg. "Today is Sunday!". The " meta-character is escaped with '\"'. String literals are null terminated (eg. with '\0'). That's why

std::cout<<sizeof("a");
prints 2.