Namespaces
Variants
Actions

Difference between revisions of "intro/constants"

From cppreference.com
(Undo revision 906 by P12 (talk))
(link to intro/escape)
Line 63: Line 63:
 
Character literals represent a single character.
 
Character literals represent a single character.
 
{{todo}}
 
{{todo}}
 +
 +
Special characters that can not be expressed directly in source code, such as the newline, can be represented using [[intro/escape|escape characters]], such as {{c|'\n'}} (a newline) or {{c|'\t'}} (a tab).
  
 
===String literals===
 
===String literals===
 
{{todo}}
 
{{todo}}

Revision as of 23:45, 6 December 2013


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.

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