Constants and Literals in C++
In this lesson: Make constants in C++ with const, constexpr and #define, and learn literal types — with examples. In Hindi & English.
Constants vs literals
A literal is a value written directly in the source code: 100, 3.14, 'A', "Priya", true. A constant is a *named* value that cannot be changed once it is set, for example const int MAX_MARKS = 100;. Constants give meaning to literals and protect them from accidental changes.
Types of literals
| Kind | Examples | Type |
|---|---|---|
| Integer | 42, -7, 1000000 | int (or larger if needed) |
| Integer, other bases | 0x2A (hex), 052 (octal), 0b101010 (binary, C++14) | int |
| Integer suffixes | 42u, 42L, 42LL, 42ULL | unsigned / long / long long |
| Floating point | 3.14, 2.5e3, 1.0f | double (float with f) |
| Character | 'A', '7', '\n', '\t' | char |
| String | "Hello", "C:\\temp" | array of const char |
| Boolean | true, false | bool |
| Pointer | nullptr | std::nullptr_t |
C++14 also allows digit separators for readability: 1'000'000 is the same as 1000000.
#include <iostream>
int main() {
std::cout << 0x2A << " " << 052 << " " << 0b101010 << "\n";
std::cout << 2.5e3 << " " << 'A' << " " << true << "\n";
std::cout << 1'000'000 << "\n";
return 0;
}Notice that true prints as 1; use std::boolalpha to print the word true.
Escape sequences in character and string literals
| Sequence | Meaning |
|---|---|
\n | New line |
\t | Tab |
\\ | Backslash |
\' and \" | Single / double quote |
\0 | Null character (end of a C string) |
The const keyword
const makes a variable read-only after it is initialised. It must be given a value when declared.
#include <iostream>
int main() {
const int MAX_MARKS = 100;
const double PASS_PERCENT = 33.0;
int obtained = 72;
double percent = obtained * 100.0 / MAX_MARKS;
std::cout << "Percent: " << percent << "\n";
std::cout << (percent >= PASS_PERCENT ? "Pass" : "Fail") << "\n";
// MAX_MARKS = 90; // error: assignment of read-only variable
return 0;
}const is also used with references and pointers (const std::string& name) and on member functions (void show() const;), which you will meet in later lessons.
constexpr: constants known at compile time
constexpr (C++11) promises that a value can be computed by the compiler. Use it for values that must be fixed before the program runs, such as array sizes.
constexpr int SUBJECTS = 5;
int marks[SUBJECTS]; // OK: size known at compile time
constexpr int square(int x) { return x * x; }
constexpr int AREA = square(4); // computed by the compiler: 16A const initialised from user input is still const, but it is not constexpr:
int n; std::cin >> n; const int size = n; // fine: cannot change later // constexpr int s2 = n; // error: n is not known at compile time
#define macros
The old C way is a preprocessor macro:
#define PI 3.14159
The preprocessor replaces every PI with 3.14159 before compilation. It has no type and no scope, and mistakes are hard to trace. In C++ prefer constexpr double PI = 3.14159;. See preprocessor directives for when macros are still useful.
enum constants
When a variable can take one of a few named values, use an enumeration:
enum class Grade { A, B, C, D, F };
Grade g = Grade::B;See enums in C++.
const vs constexpr vs #define
| Feature | #define | const | constexpr |
|---|---|---|---|
| Has a type | No | Yes | Yes |
| Obeys scope | No | Yes | Yes |
| Value fixed at compile time | Text replaced | Not necessarily | Yes, always |
| Can be array size | Yes | Only if initialised with a constant expression | Yes |
| Visible in debugger | No | Yes | Yes |
Common mistakes
- Declaring
const int x;without a value — a const must be initialised. - Writing
'Hello'(single quotes) for a string; single quotes are for one character. - Forgetting that
07and010are octal:010is 8, not 10. - Integer division surprise:
72 / 100 * 100is0; write72 * 100.0 / 100. - Using
#definefor typed constants and getting unexpected results in expressions, e.g.#define TWICE 1+1makesTWICE*3equal 4.
Write a program with constexpr int DAYS_IN_WEEK = 7, const double GST = 0.18 and an enum class Day. Read the price of an item, print it with GST, and print how many hours are in a week using the constant.
Summary
- Literals are fixed values in code; constants are named, read-only values.
- Literal kinds: integer, floating, character, string, boolean and
nullptr. const= read-only after initialisation;constexpr= known at compile time.- Prefer
const/constexprover#define. - Use
enum classfor a fixed set of named values.
Related: variables and data types, type casting, enums.
Frequently Asked Questions
What is the difference between a constant and a literal in C++?
100, 3.14, 'A' or "Aman". A constant is a named value that cannot change after it is set, such as const int MAX = 100;. Constants usually get their value from a literal.What is the difference between const and constexpr in C++?
const means the value cannot be changed after initialisation, but it may be known only at run time. constexpr means the value must be computable at compile time, so it can be used where the compiler needs a fixed number, such as an array size or a template argument.Should I use #define or const in C++?
const or constexpr. They have a type, obey scope rules and show up in the debugger. #define is plain text substitution done by the preprocessor, so it has no type checking and can cause surprising errors.What are the types of literals in C++?
42, 0x2A, 052, 0b101010), floating-point literals (3.14, 2.5e3), character literals ('A', '\n'), string literals ("Hello"), boolean literals (true, false) and the pointer literal nullptr.