Constants in C++ are fixed values that cannot be altered during program execution. They provide immutability and enhance code readability and maintainability. Understanding constants is crucial for writing robust C++ programs.
Literal constants are fixed values directly used in the code. They can be of various C++ Data Types.
int age = 30; // 30 is an integer literal constant
float pi = 3.14159; // 3.14159 is a floating-point literal constant
char grade = 'A'; // 'A' is a character literal constant
bool isTrue = true; // true is a boolean literal constant
std::string name = "John"; // "John" is a string literal constant
Const variables are declared using the const
keyword. Their values cannot be changed after initialization.
const int MAX_STUDENTS = 100;
const double TAX_RATE = 0.08;
Enumerations define a set of named integer constants.
enum Days {SUNDAY, MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY};
Days today = MONDAY;
Constants are widely used in C++ programming for various purposes:
#include <iostream>
const int MAX_ARRAY_SIZE = 5;
const double PI = 3.14159;
int main() {
int numbers[MAX_ARRAY_SIZE] = {1, 2, 3, 4, 5};
double circleArea = PI * 2 * 2; // Area of circle with radius 2
std::cout << "Array size: " << MAX_ARRAY_SIZE << std::endl;
std::cout << "Circle area: " << circleArea << std::endl;
return 0;
}
constexpr
for compile-time constants in modern C++.To deepen your understanding of C++ constants, explore these related topics:
Constants play a vital role in C++ programming. They enhance code quality, prevent accidental modifications, and improve program reliability. By mastering the use of constants, you'll write more robust and maintainable C++ code.