C++ Constants and Literals
Constants are fixed values that cannot be changed during program execution. Literals are fixed values directly written in the code such as numbers, characters, or strings.
1. Constants in C++
Constants can be declared using the const keyword, #define preprocessor directive, or constexpr (C++11).
2. Using const Keyword
The const keyword makes a variable read-only after initialization.
C++
Example using const
#include <iostream>
using namespace std;
int main() {
const int age = 25;
// age = 30; // Error: cannot modify const variable
cout << "Age: " << age;
return 0;
}
3. Using #define
#define creates symbolic constants using the preprocessor.
C++
Example using #define
#include <iostream>
using namespace std;
#define PI 3.14159
int main() {
cout << "Value of PI: " << PI;
return 0;
}
4. Using constexpr (C++11)
constexpr ensures that a variable or function is evaluated at compile time.
C++
Example using constexpr
#include <iostream>
using namespace std;
constexpr int square(int x) {
return x * x;
}
int main() {
constexpr int value = square(5);
cout << "Square: " << value;
return 0;
}
5. Types of Literals in C++
- Integer Literals - 10, 100, 0xFF
- Floating-point Literals - 3.14, 2.5e3
- Character Literals - 'A', 'b'
- String Literals - "Hello"
- Boolean Literals - true, false
6. Literal Examples
C++
Example demonstrating different literals
#include <iostream>
using namespace std;
int main() {
int num = 100; // Integer literal
float price = 99.99f; // Floating literal
char grade = 'A'; // Character literal
string name = "CodeCrown"; // String literal
bool isActive = true; // Boolean literal
cout << "Integer: " << num << endl;
cout << "Float: " << price << endl;
cout << "Char: " << grade << endl;
cout << "String: " << name << endl;
cout << "Boolean: " << isActive << endl;
return 0;
}
7. Complete Example Program
C++
Program using constants and literals
#include <iostream>
using namespace std;
#define COMPANY "CodeCrown"
int main() {
const int year = 2026;
constexpr double pi = 3.14159;
cout << "Company: " << COMPANY << endl;
cout << "Year: " << year << endl;
cout << "PI Value: " << pi << endl;
cout << "Boolean Literal: " << true << endl;
return 0;
}
Conclusion
Constants ensure that values remain fixed, improving code safety and readability. Literals represent fixed values directly written in the program. Modern C++ recommends using const and constexpr instead of #define whenever possible.
Codecrown