Constants
Sometimes, we want a value that never changes while the program is running. That’s what constants are for!
Constants help prevent mistakes (like changing a number by accident) and make the code easier to understand.
Example: Regular variable vs constant
#include <iostream>
using namespace std;
int main() {
int age = 15;
age = 16; // we can change it
const double PI = 3.14159;
// PI = 3.14; Error! cannot change a constant
cout << "PI is " << PI << endl;
return 0;
}Output:
PI is 3.14159
Why use constants?
- To protect important values from being changed by accident.
- To make code more readable —
PIis clearer than3.14159.
- To update easily — if
PIever changes (it won’t, but you get the point), you just change it in one place.
Declaring constants
You make a constant by adding the keyword const before the type:
const int DAYS_IN_WEEK = 7;
const double GRAVITY = 9.81;
const char GRADE = 'A';Constants must always be given a value at the moment they are declared.
Literal constants
Literal constants are values that appear directly in the code, like:
int x = 5; // 5 is an integer literal
double pi = 3.14; // 3.14 is a double literal
char letter = 'A'; // 'A' is a character literal
string word = "Hi"; // "Hi" is a string literalThese are just raw values written in your code.
Common literal suffixes
You can tell C++ what type a number literal should be using suffixes:
| Literal | Type | Meaning |
|---|---|---|
5 |
int |
default integer |
5U |
unsigned int |
no negative values |
5L |
long |
long integer |
5LL |
long long |
very large integer |
3.14f |
float |
single-precision decimal |
3.14 |
double |
default for decimals |
3.14L |
long double |
high precision decimal |
Example:
float a = 3.14f;
long long b = 10000000000LL;
long double c = 3.1415926535L;If you omit the suffix, C++ will assume int for whole numbers and double for decimals.
Constants with #define (old way)
Before const existed, people used #define to create constants:
#define PI 3.14159
#define GREETING "Hello"It still works, but const is safer and preferred in modern C++.
Summary table
| Method | Example | Can change? | When to use |
|---|---|---|---|
const |
const int x = 5; |
No | Always for fixed values |
#define |
#define Z 15 |
No | Old style, avoid in modern C++ |
Quick recap
- Use
constfor values that should never change.
- Use suffixes like
LLorfto pick the right numeric type.
- Avoid
#definefor constants unless you are reading old code.
With constants, your code becomes safer, clearer, and easier to maintain.