C++ Constants, Literals, and Variable Rules
Master C++ constants, literals, tokens, and variable rules. Learn about const, constexpr, variable scope, naming conventions, and storage classes with practical examples.
Constants
const & constexpr
Literals
Numeric & String
Tokens
Keywords & Identifiers
Variables
Rules & Scope
1. Constants in C++
Constants are fixed values that cannot be altered during program execution. C++ provides several ways to define constants.
Using const Keyword
The const keyword specifies that a variable's value is constant and tells the compiler to prevent modification.
const int MAX_SIZE = 100;
const double PI = 3.14159;
const std::string GREETING = "Hello";
Using constexpr (C++11)
constexpr specifies that the value is constant and can be evaluated at compile-time.
constexpr int ARRAY_SIZE = 100;
constexpr double EULER = 2.71828;
constexpr int SQUARE(int x) { return x * x; }
const vs constexpr
const indicates "read-only" while constexpr indicates "compile-time constant". All constexpr objects are const, but not all const objects are constexpr.
#include <iostream>
#include <string>
using namespace std;
int main() {
// const variables
const int MAX_STUDENTS = 50;
const double TAX_RATE = 0.15;
const string COMPANY_NAME = "TechCorp";
// constexpr variables (compile-time constants)
constexpr int ARRAY_LENGTH = 100;
constexpr double PI = 3.1415926535;
// Pointers to constants
const int* ptr = &MAX_STUDENTS; // Pointer to constant int
int* const ptr2 = new int(5); // Constant pointer to int
// Constant member functions
// (Will be covered in OOP section)
cout << "Max Students: " << MAX_STUDENTS << endl;
cout << "PI Value: " << PI << endl;
cout << "Company: " << COMPANY_NAME << endl;
// MAX_STUDENTS = 60; // Error: cannot modify const
delete ptr2;
return 0;
}
2. Literals in C++
Literals are constant values used directly in the code. They can be of various types including integer, floating-point, character, and string literals.
| Literal Type | Description | Examples |
|---|---|---|
| Integer Literals | Whole numbers without fractional part | 42, 0xFF, 075, 0b1010 |
| Floating-point | Numbers with decimal point or exponent | 3.14, 2.5e-3, 1.0f |
| Character Literals | Single character enclosed in single quotes | 'A', '\n', '\x41', '\u0041' |
| String Literals | Sequence of characters in double quotes | "Hello", "C++\n", R"(Raw String)" |
| Boolean Literals | Logical true/false values | true, false |
| Null Pointer | Pointer that doesn't point to anything | nullptr (C++11) |
#include <iostream>
#include <string>
using namespace std;
int main() {
// Integer literals (decimal, octal, hexadecimal, binary)
int decimal = 42;
int octal = 052; // 0 prefix for octal
int hexadecimal = 0x2A; // 0x prefix for hex
int binary = 0b101010; // 0b prefix for binary (C++14)
// Floating-point literals
float pi_float = 3.14f; // f suffix for float
double pi_double = 3.14159; // default is double
long double pi_long = 3.1415926535L; // L suffix for long double
// Character literals
char letter = 'A';
char newline = '\n';
char tab = '\t';
char unicode = '\u0041'; // Unicode for 'A'
// String literals
string greeting = "Hello, World!";
string path = "C:\\Program Files\\";
string raw = R"(Line 1\nLine 2)"; // Raw string (C++11)
// Boolean literals
bool isReady = true;
bool isFinished = false;
// Output examples
cout << "Decimal: " << decimal << endl;
cout << "Hex (0x2A): " << hexadecimal << endl;
cout << "Float PI: " << pi_float << endl;
cout << "Greeting: " << greeting << endl;
cout << "Is Ready: " << boolalpha << isReady << endl;
return 0;
}
U for unsigned, L for long, LL for long long, F for float, and L for long double. Example: 100UL (unsigned long), 3.14F (float).
3. Tokens in C++
Tokens are the smallest individual elements in a C++ program. The compiler breaks code into tokens during compilation.
Keywords
Reserved words with special meaning. Cannot be used as identifiers.
int, float, doubleif, else, switchfor, while, do
class, struct, enumconst, static, autopublic, private
Identifiers
Names given to variables, functions, classes, etc. Must follow naming rules.
myVariablecalculateAreaMAX_SIZE
123varmy-varfloat
- Can contain letters (a-z, A-Z), digits (0-9), and underscores (_)
- Must begin with a letter or underscore (not a digit)
- Cannot be a C++ keyword
- Case-sensitive (
myVar≠MyVar) - No special characters except underscore
| Token Type | Description | Examples |
|---|---|---|
| Keywords | Predefined reserved words | int, class, return, if, for |
| Identifiers | Names defined by programmer | variableName, calculateTotal, Student |
| Constants/Literals | Fixed values | 100, 3.14, 'A', "Hello" |
| Operators | Symbols that perform operations | +, -, *, /, =, ==, &, -> |
| Punctuators | Syntax elements | ;, ,, ., :, {}, [], () |
4. Variable Rules and Scope
Variables are named storage locations. Understanding variable rules, scope, and lifetime is essential for writing correct C++ programs.
Variable Declaration and Initialization
#include <iostream>
using namespace std;
// Global variable (accessible throughout file)
int globalVar = 100;
int main() {
// Declaration (telling compiler about variable)
int age;
// Initialization (giving initial value)
int score = 95;
// Multiple declarations
int x = 5, y = 10, z = 15;
// Using auto (type inference - C++11)
auto name = "John"; // const char*
auto price = 99.99; // double
auto isAvailable = true; // bool
// Using decltype (declares type from expression - C++11)
int value = 42;
decltype(value) copy = value; // copy is also int
// Reference variable (alias for another variable)
int original = 50;
int& ref = original; // ref is reference to original
// Constant reference
const int& constRef = original; // Cannot modify through constRef
cout << "Score: " << score << endl;
cout << "Auto type name: " << name << endl;
cout << "Reference: " << ref << endl;
return 0;
}
Variable Scope
| Scope Type | Description | Example & Lifetime |
|---|---|---|
| Local Scope | Declared inside a function or block. Accessible only within that block. | void func() { int x = 5; }Lifetime: Block execution |
| Global Scope | Declared outside all functions. Accessible throughout the file. | int global = 10;Lifetime: Entire program |
| Function Parameter | Declared in function parameter list. Local to the function. | void print(int num) { ... }Lifetime: Function execution |
| Class Scope | Declared inside a class. Access depends on access specifier. | class MyClass { int data; };Lifetime: Object lifetime |
| Namespace Scope | Declared inside a namespace. Access using namespace qualification. | namespace MyNS { int value; }Lifetime: Program |
Storage Classes
auto (default)
Default for local variables. Automatic storage duration.
auto int x; (obsolete)auto y = 5; (C++11 type inference)
static
Retains value between function calls. Lifetime: entire program.
static int counter = 0;Preserves value across calls
extern
Declares variable defined elsewhere. Used for sharing between files.
extern int globalVar;Defined in another file
register
Hint to store in register (largely obsolete with modern compilers).
register int fast;Compiler may ignore
- Using uninitialized variables (contains garbage values)
- Scope confusion (accessing variables outside their scope)
- Name shadowing (local variable hides global variable with same name)
- Forgetting to free dynamically allocated memory
- Using dangling references or pointers
5. Best Practices
Do's
- Use
constfor values that shouldn't change - Use
constexprfor compile-time constants - Initialize variables when declaring them
- Use meaningful, descriptive names
- Follow naming conventions (camelCase, PascalCase, UPPER_CASE)
- Limit variable scope as much as possible
- Use
autowhen type is obvious from initialization
Don'ts
- Don't use global variables unnecessarily
- Don't use magic numbers (use named constants)
- Don't use single-letter names except for counters
- Don't declare all variables at the top (old C style)
- Don't use
registerkeyword (obsolete) - Don't use Hungarian notation in modern C++
- Don't use
#definefor constants (useconst)
Naming Convention Examples
camelCase: studentName, calculateAverage
PascalCase: StudentName, CalculateAverage (classes, functions)
snake_case: student_name, calculate_average
UPPER_CASE: MAX_SIZE, PI_VALUE (constants)
Choose one style and be consistent throughout your project.
// Good practices demonstrated
#include <iostream>
#include <string>
using namespace std;
// Constants in UPPER_CASE
constexpr int MAX_STUDENTS = 50;
constexpr double PI = 3.1415926535;
const string DEFAULT_NAME = "Unknown";
// Function names in PascalCase
double CalculateCircleArea(double radius) {
return PI * radius * radius;
}
int main() {
// Variables in camelCase, initialized
int studentCount = 0;
double circleRadius = 5.5;
string studentName = DEFAULT_NAME;
// Limit scope - declare near first use
{
int temporaryValue = 42;
cout << "Temp: " << temporaryValue << endl;
} // temporaryValue destroyed here
// auto when type is obvious
auto area = CalculateCircleArea(circleRadius);
auto message = "Area calculated"; // const char*
// const reference to avoid copy
const auto& nameRef = studentName;
cout << "Circle area: " << area << endl;
cout << "Max students allowed: " << MAX_STUDENTS << endl;
return 0;
}