Chapter 05 of 48

Constants & Literals

In the previous chapter, Variables & Data Types, we stored values in variables that could change. But some values should never change while a program runs: the value of π, the maximum marks in an exam, the number of days in a week. And every time we write 20, 8.75, 'A' or "Neha" in our code, we are writing a literal.

This chapter covers both ideas: how to make values constant with const, constexpr and friends, and every kind of literal C++ offers, including what type each literal has (a favourite source of tricky exam questions).


Literals vs Constants

A literal is a fixed value written directly in the source code, such as 42, 3.14, 'A' or "hello".

A constant is a named value that cannot be changed after it is initialised, such as const int MAX_MARKS = 100;.

const int MAX_MARKS = 100;
          ─────────   ───
          constant    literal
          (a name)    (the value written in code)

Why use named constants instead of writing 100 everywhere? A bare number like 100 in the middle of code is called a magic number: a reader cannot tell whether it means maximum marks, a percentage or an array size. A named constant explains itself, and if the value ever changes you update it in one place.


The const Keyword

Putting const before (or after) the type makes a variable read-only:

#include <iostream>

int main() {
    const double PI = 3.14159;
    const int MAX_MARKS = 100;

    double r = 2.0;
    std::cout << "Area = " << PI * r * r << '\n';
    std::cout << "Max marks = " << MAX_MARKS << '\n';

    // PI = 3.14;   // error: assignment of read-only variable 'PI'
}

Output:

Area = 12.5664
Max marks = 100

Two rules follow from "read-only":

int main() {
    const int MAX_MARKS = 100;
    MAX_MARKS = 90;
    const int LIMIT;
    return MAX_MARKS + LIMIT;
}
main.cpp: In function ‘int main()’:
main.cpp:3:15: error: assignment of read-only variable ‘MAX_MARKS’
    3 |     MAX_MARKS = 90;
      |     ~~~~~~~~~~^~~~
main.cpp:4:15: error: uninitialized ‘const LIMIT’ [-fpermissive]
    4 |     const int LIMIT;
      |               ^~~~~
  1. You cannot assign to a const variable after it is created.

  2. A const variable must be initialised when it is declared, because there would be no other chance to give it a value.

const int and int const mean exactly the same thing. A common naming style for constants is UPPER_CASE, though many modern codebases use kMaxMarks or ordinary names. You will see const again with pointers, references, function parameters and member functions in later chapters.


constexpr: Constants Known at Compile Time (C++11)

A const variable only promises "I will not change". Its value may still be computed at run time, for example from user input. Sometimes we need a value that the compiler knows while compiling: for an array size, a static_assert, or a template argument. That is what constexpr is for.

constexpr on a variable means its value must be computable at compile time. constexpr on a function means it can be evaluated at compile time when its arguments are constants.

#include <iostream>

constexpr int square(int n) { return n * n; }   // C++11

int main() {
    constexpr int SIZE = 5;                  // known at compile time
    int marks[SIZE] = {70, 85, 90, 65, 88};  // OK: array size must be a constant

    constexpr int AREA = square(SIZE);       // computed by the compiler
    static_assert(AREA == 25);               // checked at compile time (C++17 form)

    int n;
    std::cin >> n;
    const int fromUser = n;                  // const, but known only at run time
    int answer = square(fromUser);           // same function, called at run time

    std::cout << marks[0] << ' ' << AREA << ' ' << answer << '\n';
}

Input 7, output:

70 25 49

Notice that the same square function was used twice: once by the compiler (square(SIZE), because SIZE is a compile-time constant) and once at run time (square(fromUser)). static_assert checks a condition during compilation; if it is false, the program does not compile. (Writing static_assert without a message needs C++17.)

A constexpr variable cannot be initialised from a value that is only known at run time:

int main() {
    int n = 10;
    constexpr int a = n;   // error: n is not a constant expression
    return a;
}
main.cpp: In function ‘int main()’:
main.cpp:3:23: error: the value of ‘n’ is not usable in a constant expression
    3 |     constexpr int a = n;   // error: n is not a constant expression
      |                       ^
main.cpp:2:9: note: ‘int n’ is not const
    2 |     int n = 10;
      |         ^

const vs constexpr

Pointconstconstexpr
MeaningCannot be modified after initialisationValue is known at compile time (and the variable is also const)
InitialiserAny value, even from user inputMust be a constant expression
Usable as array size / template argumentOnly if it happens to be initialised with a constant expression (integer types)Always
Applies to functions?Not in this senseYes: constexpr functions
SinceC++98C++11 (much more powerful since C++14)

Simple rule: use constexpr for values that are truly fixed when you write the program, and const for values that are computed at run time but must not change afterwards.

consteval and constinit (C++20)

C++20 added two related keywords that you will see in modern code:

  • consteval makes a function an immediate function: every call must be evaluated at compile time.

  • constinit on a global or static variable guarantees that it is initialised at compile time, but the variable is not const and can change later. It is mainly used to avoid problems with the order in which global variables are initialised.

#include <iostream>

consteval int cube(int n) { return n * n * n; }  // C++20: compile time ONLY

int main() {
    constexpr int c = cube(3);   // OK
    std::cout << c << '\n';
    int x = 4;
    // int y = cube(x);          // error: x is not a constant expression
    std::cout << cube(2) + x << '\n';
}

Output:

27
12

cube(2) is fine because 2 is a constant; cube(x) would not compile because x is an ordinary variable.


The Old Way: #define

In C, constants were usually created with the preprocessor:

#define PI 3.14159

This still works in C++, but a macro is plain text replacement done before compilation. It has no type, it ignores scopes and namespaces, and it can produce surprising results:

#include <iostream>

#define SIZE_MACRO 2 + 3        // a macro is just text replacement
constexpr int SIZE_CONST = 2 + 3;

int main() {
    std::cout << SIZE_MACRO * 10 << '\n';   // becomes 2 + 3 * 10
    std::cout << SIZE_CONST * 10 << '\n';   // 5 * 10
}

Output:

32
50

The macro version printed 32, because SIZE_MACRO * 10 was replaced by the text 2 + 3 * 10, and * is evaluated before +. The constexpr version is a real value of type int, so it gave 50.

#defineconst / constexpr
Handled by the preprocessorHandled by the compiler
No type checkingHas a proper type
Ignores scope and namespacesFollows normal scope rules
Usually invisible in a debuggerCan be inspected
Risk of precedence surprisesBehaves like a normal value

In modern C++, prefer constexpr (or const) for constants. Macros are still used for things like include guards and conditional compilation. A third way to name a set of related constants is an enumeration, covered in Structures, Unions & Enums.


Integer Literals

An integer literal can be written in four bases:

BasePrefixExample (all equal 42)Since
Decimal (base 10)none42C++98
Octal (base 8)0052C++98
Hexadecimal (base 16)0x or 0X0x2AC++98
Binary (base 2)0b or 0B0b101010C++14

C++14 also added the digit separator ', which the compiler ignores. It only makes long numbers readable:

#include <iostream>

int main() {
    int dec = 42;          // decimal
    int oct = 052;         // octal (leading 0)
    int hex = 0x2A;        // hexadecimal (0x or 0X)
    int bin = 0b101010;    // binary (0b or 0B), C++14

    std::cout << dec << ' ' << oct << ' ' << hex << ' ' << bin << '\n';

    long long population = 1'428'627'663;   // digit separators, C++14
    int mask = 0b1111'0000;
    std::cout << population << ' ' << mask << '\n';

    std::cout << std::hex << 255 << ' ' << std::oct << 8 << ' ' << std::dec << 010 << '\n';
}

Output:

42 42 42 42
1428627663 240
ff 10 8

The last line shows the manipulators std::hex and std::oct, which print in other bases (255 in hex is ff, 8 in octal is 10). And it shows the classic trap: 010 is octal, so it equals 8, not 10. Never write a leading zero on a decimal number. (By the way, 0 itself is technically an octal literal, which does not matter because zero is zero in every base.)

The working of octal and hex, step by step:

052  (octal) = 5 × 8^1  + 2 × 8^0  = 40 + 2  = 42
0x2A (hex)   = 2 × 16^1 + A × 16^0 = 32 + 10 = 42   (A = 10, ..., F = 15)
0b101010     = 32 + 8 + 2                    = 42

Suffixes and the type of an integer literal

Every literal has a type. A suffix lets you choose it:

SuffixTypeExample
noneint (if the value fits)42
u / Uunsigned int42u
l / Llong42L
ul / ULunsigned long42UL
ll / LLlong long42LL
ull / ULLunsigned long long42ULL
z / Z (C++23)signed version of std::size_t42z
uz / UZ (C++23)std::size_t42uz

Prefer capital L: a small l looks almost identical to the digit 1 (10l vs 101).

If a literal with no suffix is too large for int, the compiler picks the first type in a list that can hold it. For a decimal literal, the list is int → long → long long. For octal, hex and binary literals, the unsigned types are also tried: int → unsigned int → long → unsigned long → long long → unsigned long long.

We can prove all of this with static_assert and decltype (which gives the type of an expression). This program compiles without errors, so every line is true on 64-bit Linux:

#include <cstddef>
#include <type_traits>

// Each line is checked by the compiler. If any of them were false,
// the program would not compile.
static_assert(std::is_same_v<decltype(42),    int>);
static_assert(std::is_same_v<decltype(42u),   unsigned int>);
static_assert(std::is_same_v<decltype(42L),   long>);
static_assert(std::is_same_v<decltype(42UL),  unsigned long>);
static_assert(std::is_same_v<decltype(42LL),  long long>);
static_assert(std::is_same_v<decltype(42ULL), unsigned long long>);
static_assert(std::is_same_v<decltype(42uz),  std::size_t>);        // C++23
static_assert(std::is_same_v<decltype(3.14),  double>);
static_assert(std::is_same_v<decltype(3.14f), float>);
static_assert(std::is_same_v<decltype(3.14L), long double>);
static_assert(std::is_same_v<decltype('A'),   char>);
static_assert(std::is_same_v<decltype(u8'A'), char8_t>);            // C++20
static_assert(std::is_same_v<decltype(true),  bool>);
static_assert(std::is_same_v<decltype(nullptr), std::nullptr_t>);

// A decimal literal too big for int becomes long (on 64-bit Linux):
static_assert(std::is_same_v<decltype(3000000000), long>);
// A hex literal of the same size may become unsigned int instead:
static_assert(std::is_same_v<decltype(0xB2D05E00), unsigned int>);

int main() {}

On 64-bit Windows, long is only 32 bits, so 3000000000 becomes long long there.

Why do suffixes matter? Because the type of the literal decides how the calculation is done. 100000 * 100000 is computed in int and overflows (undefined behavior), but 100000LL * 100000 is computed in long long and gives 10,000,000,000 correctly.


Floating-Point Literals

#include <iostream>

int main() {
    double a = 3.14;
    double b = 2.5e3;      // 2.5 × 10^3
    double c = 1.6e-19;    // 1.6 × 10^-19
    double d = .5;         // 0.5
    double e = 5.;         // 5.0
    float  f = 3.14f;      // float literal
    double h = 0x1.8p1;    // hexadecimal float, C++17: 1.5 × 2^1

    std::cout << a << ' ' << b << ' ' << c << ' ' << d << ' '
              << e << ' ' << f << ' ' << h << '\n';
    std::cout << 10 / 4 << ' ' << 10 / 4.0 << ' ' << 10.0f / 4 << '\n';
}

Output:

3.14 2500 1.6e-19 0.5 5 3.14 3
2 2.5 2.5
  • A floating-point literal has a decimal point or an exponent. 2.5e3 means 2.5 × 103.

  • With no suffix, the type is double. The suffix f/F gives float, and l/L gives long double.

  • Writing float f = 3.14; converts a double literal to float. With braces, float f{3.14}; is still allowed because 3.14 is a constant whose value fits in the float range; the narrowing rule only rejects constants that are out of range or variables. Using 3.14f makes your intent clear.

  • Hexadecimal floating literals (C++17), like 0x1.8p1, describe a binary value exactly: 1.8 in hex is 1.5 in decimal, and p1 means × 21, giving 3. They are mostly used in numerical libraries.


Character Literals and Escape Sequences

A character literal is one character in single quotes: 'A', '7', ' '. Its type is char (in C it would be int). Some characters cannot be typed directly, so we use an escape sequence starting with a backslash:

EscapeMeaning
\nNewline
\tHorizontal tab
\\Backslash
\'Single quote
\"Double quote
\0Null character (value 0), which ends C-style strings
\rCarriage return
\aAlert (bell)
\bBackspace
\oooCharacter with octal code ooo (up to 3 digits), e.g. \101 = 'A'
\xhhCharacter with hexadecimal code hh (one or more hex digits), e.g. \x42 = 'B'
#include <iostream>

int main() {
    std::cout << "Tab:\tafter tab\n";
    std::cout << "Quote: \"C++\"\n";
    std::cout << "Single quote: \'\n";
    std::cout << "Backslash: C:\\Users\\riya\n";
    std::cout << "Octal \101 and hex \x42\n";   // 'A' is 65 = 0101 octal, 'B' is 0x42
    std::cout << 'A' << ' ' << static_cast<int>('A') << ' '
              << static_cast<int>('0') << ' ' << static_cast<int>('\n') << '\n';
    std::cout << 'A' + 1 << '\n';                // char + int gives int
}

Output:

Tab:	after tab
Quote: "C++"
Single quote: '
Backslash: C:\Users\riya
Octal A and hex B
A 65 48 10
66

Look at the last line: 'A' + 1 printed 66, not B. In arithmetic, a char is promoted to int, and std::cout prints an int as a number. (In Variables & Data Types, char next = c + 1; printed B because the result was stored back into a char.)

C++23 also added delimited escapes, where braces mark exactly where the code ends: "\o{101}" (octal), "\x{42}" (hex) and "\u{43}" (Unicode code point) give A, B and C. It also added named escapes such as "\N{LATIN CAPITAL LETTER D}", which gives D. These avoid the classic trap where "\x41BC" is read as one (too large) hex escape instead of A followed by BC.

For Unicode text, C++ has prefixed character literals: u8'A' (type char8_t, C++20; earlier it was char), u'A' (char16_t), U'A' (char32_t) and L'A' (wchar_t).


String Literals

A string literal is text in double quotes. Its type is an array of const char that includes a hidden null character '\0' at the end. So "Hi" has type const char[3]:

"Hi"  →  ┌─────┬─────┬──────┐
         │ 'H' │ 'i' │ '\0' │     3 chars, read-only
         └─────┴─────┴──────┘
#include <iostream>
#include <string>

int main() {
    std::cout << sizeof("Hi") << '\n';           // 3: 'H', 'i' and the hidden '\0'

    std::cout << "Hello, " "World" "!\n";        // adjacent literals are joined

    // Raw string literal (C++11): backslashes and quotes are taken literally
    std::cout << R"(C:\new\table "quoted")" << '\n';
    std::cout << R"(Line one
Line two)" << '\n';
    std::cout << R"xyz(contains )" inside)xyz" << '\n';

    using namespace std::string_literals;        // C++14
    auto s = "abc"s;                             // std::string, not const char*
    std::cout << s.size() << ' ' << s + "def" << '\n';
}

Output:

3
Hello, World!
C:\new\table "quoted"
Line one
Line two
contains )" inside
3 abcdef
  • sizeof("Hi") is 3 because of the hidden '\0'.

  • String literals placed next to each other are joined by the compiler into one literal. This is useful for splitting long text over several lines.

  • Raw string literals (C++11) start with R"( and end with )". Everything in between is taken exactly as written: backslashes are not escapes and newlines are kept. They are perfect for Windows paths and regular expressions. If the text itself contains )", add your own delimiter, as in R"xyz( ... )xyz".

  • A plain string literal is not a std::string. With the s suffix from std::string_literals (C++14), "abc"s is a real std::string, so you can call .size() and use +.

String literals are read-only

Since C++11, it is not allowed to point a plain char* at a string literal. GCC still accepts it as an extension, but warns:

int main() {
    char* p = "hello";   // not allowed since C++11
    p[0] = 'H';
}
main.cpp: In function ‘int main()’:
main.cpp:2:15: warning: ISO C++ forbids converting a string constant to ‘char*’ [-Wwrite-strings]
    2 |     char* p = "hello";   // not allowed since C++11
      |               ^~~~~~~

With -pedantic-errors (strict standard mode), this warning becomes an error. And if you ignore the warning and run the program, writing into the literal is undefined behavior. On our Linux machine, running ./main; echo "exit: $?" in bash printed (the number before "Segmentation fault" is the process ID and changes each run):

bash: line 1:  6408 Segmentation fault         ./main
exit: 139

(Exit status 139 means the process was killed by signal 11, a segmentation fault, because string literals are stored in read-only memory.) If you need a modifiable string, use std::string s = "hello"; or a char array: char s[] = "hello";. Both make a copy of the literal that you own.


Boolean and Pointer Literals

The two bool literals are true and false:

#include <iostream>

int main() {
    std::cout << true << ' ' << false << '\n';
    std::cout << std::boolalpha << true << ' ' << false << '\n';
    std::cout << (true + true) << '\n';    // bool promotes to int: 1 + 1
}

Output:

1 0
true false
2

nullptr (C++11) is the null pointer literal, meaning "a pointer that points to nothing". Older code used 0 or the macro NULL, but those are integers, which leads to confusing behavior when functions are overloaded:

#include <iostream>

void show(int)   { std::cout << "show(int)\n"; }
void show(int*)  { std::cout << "show(int*)\n"; }

int main() {
    show(0);          // 0 is an int literal
    show(nullptr);    // nullptr is a null pointer literal (C++11)
}

Output:

show(int)
show(int*)

0 chose the int version, while nullptr chose the pointer version, as intended. Always use nullptr in modern C++. Pointers are covered in detail in Pointers, and overloading in Function Overloading.


User-Defined Literals (C++11)

C++ lets libraries define their own literal suffixes. You already saw "abc"s. Another useful set comes from <chrono> for time durations (C++14):

#include <chrono>
#include <iostream>

int main() {
    using namespace std::chrono_literals;   // C++14
    auto total = 2h + 30min + 15s;           // a std::chrono::seconds value
    std::cout << total << '\n';              // printing durations needs C++20
    std::cout << std::chrono::duration_cast<std::chrono::minutes>(total) << '\n';
}

Output:

9015s
150min

2 hours + 30 minutes + 15 seconds = 9015 seconds = 150 whole minutes (the 15 seconds are dropped by duration_cast). Printing a duration directly with << needs C++20. You can write your own suffixes too, but suffixes that don't start with an underscore are reserved for the standard library.


Summary Table of Literals

LiteralExampleType
Decimal integer42int
Integer with suffix42u, 42L, 42LL, 42uzunsigned int, long, long long, std::size_t
Octal / hex / binary052, 0x2A, 0b101010int (if it fits)
Floating-point3.14, 2.5e3double
Float / long double3.14f, 3.14Lfloat, long double
Character'A', '\n'char
UTF-8 characteru8'A'char8_t (C++20)
String"Hi"const char[3]
Raw stringR"(C:\new)"const char[N]
std::string literal"Hi"sstd::string (C++14)
Booleantrue, falsebool
Null pointernullptrstd::nullptr_t (C++11)

Common Mistakes

  • Writing a leading zero: int code = 010; is 8, not 10. And 09 does not compile at all, because 9 is not an octal digit.

  • Overflow in a calculation with literals: long long big = 1000000 * 1000000; overflows before the assignment, because both literals are int. Write 1000000LL * 1000000.

  • Confusing 'A' and "A": the first is one char; the second is a string of two characters ('A' and '\0').

  • Single backslashes in Windows paths: "C:\new" contains a newline. Use "C:\\new" or R"(C:\new)".

  • Modifying a string literal through a pointer: undefined behavior.

  • Forgetting to initialise a const, or trying to make a constexpr from a runtime value.

  • Using #define constants without parentheses, causing precedence surprises. Prefer constexpr.


Interview / GATE Questions

What is the difference between const and constexpr?

const means the object cannot be modified after initialisation, but its value may be decided at run time. constexpr requires the value to be a compile-time constant, so it can be used for array sizes, template arguments and static_assert. A constexpr variable is automatically const.

What is printed by std::cout << 012 + 0x12 + 0b11;?

31. Octal 012 is 10, hex 0x12 is 18, binary 0b11 is 3, and 10 + 18 + 3 = 31.

What is the type of the literal 3.0? Of 3.0f? Of '3'?

double, float and char.

What is sizeof("GATE")?

5. The literal has type const char[5]: four letters plus the terminating '\0'.

Why is nullptr better than NULL?

NULL is an integer constant (such as 0), so it can match an int overload instead of a pointer one. nullptr has its own type, std::nullptr_t, which converts to any pointer type but not to integers, so overload resolution picks the pointer version.

Why can #define SQUARE(x) x * x give a wrong answer for SQUARE(2 + 3)?

It expands as text to 2 + 3 * 2 + 3, which is 11, not 25. Macros do not respect operator precedence. A constexpr function constexpr int square(int x) { return x * x; } has no such problem.

Can a const variable be used as the size of an array?

Yes, if it is of integer type and initialised with a constant expression, as in const int N = 5; int a[N];. If it is initialised from a runtime value, it is not a constant expression and cannot be used. constexpr makes the intent explicit and is checked by the compiler.


In Simple Words

A literal is a value written directly in code, and every literal has a type. A constant is a name for a value that cannot change: use constexpr when the value is known at compile time and const when it is only known at run time.

const int a = x;        → read-only, value may come from run time
constexpr int b = 5;    → compile-time constant (C++11)
consteval f()           → function always evaluated at compile time (C++20)
42 / 052 / 0x2A / 0b101010 → same number in decimal / octal / hex / binary
1'000'000               → digit separators (C++14)
42LL, 42u, 42uz         → long long, unsigned int, size_t (C++23)
3.14 → double, 3.14f → float, 'A' → char, "A" → const char[2]
R"(C:\path)"            → raw string (C++11)
nullptr                 → null pointer literal (C++11)

Next, in Input & Output, we will read values from the keyboard with std::cin and learn how to format output neatly.