← Back to C++ Course | Chapter 1: Introduction & Basics | Lesson 15 of 15

C++ Constants

The const Keyword

The const keyword tells the compiler that a variable's value must never change after it's initialized, and any attempt to assign to it later is caught as a compile-time error rather than a runtime bug. This is useful for values like a tax rate or an array size that should be fixed and protected from accidental modification elsewhere in the code.

Example: The const Keyword

cpp
#include <iostream>

int main() {
	const double taxRate = 0.08;
	std::cout << "Tax rate: " << taxRate << std::endl;
	return 0;
}

Constant Expressions (constexpr)

constexpr goes a step further than const by requiring the value to be computable entirely at compile time, which lets the compiler substitute the literal result directly into the generated machine code instead of computing it while the program runs. This can measurably improve performance for values used in tight loops or as array sizes.

Example: Constant Expressions (constexpr)

cpp
#include <iostream>

constexpr int arraySize = 10; // computed entirely at compile time

int main() {
	int values[arraySize];
	std::cout << "Array size: " << arraySize << std::endl;
	return 0;
}

Literals

A literal is a value written directly into your source code exactly as it will be used — 42, 3.14, A, and "hello" are all literals of type int, double, char, and string respectively. Literals are distinct from named constants: a literal has no name of its own, while a constant gives a literal a readable, reusable label.

Example: Literals

cpp
#include <iostream>

int main() {
	std::cout << 42 << " " << 3.14 << " " << 'A' << " " << "hello" << std::endl;
	return 0;
}

Defining Constants with #define

#define is a preprocessor directive that performs a pure text substitution before compilation even begins, replacing every occurrence of the defined name with its value throughout the file. Because it happens at the text level rather than through the type system, modern C++ generally prefers const or constexpr, which are type-checked and easier to debug.

Example: Defining Constants with #define

cpp
#include <iostream>
#define MAX_USERS 100

int main() {
	std::cout << "Max users: " << MAX_USERS << std::endl;
	return 0;
}

Constant Best Practices

Writing constant names in ALL_CAPS, like MAX_USERS or PI, makes them instantly recognizable as fixed values whenever they appear in code, distinguishing them at a glance from ordinary variables. Grouping related constants together near the top of a file also makes it easy to find and update configuration-like values in one place.

Example: Constant Best Practices

cpp
#include <iostream>
const double PI = 3.14159;
const int MAX_USERS = 100;

int main() {
	std::cout << PI << " " << MAX_USERS << std::endl;
	return 0;
}

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.