Constant Variables
Anonymous contributor
Published Nov 9, 2024
Contribute to Docs
Constant variables in C++ are variables whose values cannot be altered after they are set. By using the const
keyword, a variable becomes read-only, preventing accidental modification. Constants are especially useful for defining values that should remain consistent throughout the program, such as mathematical constants (e.g., PI
) or configuration settings.
Syntax
const data_type variable_name = value;
data_type
: The type of the variable.variable_name
: The name of the constant variable.value
: The initial value assigned to the variable. Once set, this value cannot change.
Example
This example demonstrates how to declare and use a constant variable in C++:
#include <iostream>int main() {const int max_attempts = 5;std::cout << "Maximum allowed attempts: " << max_attempts << std::endl;// Uncommenting the following line would cause a compilation error// max_attempts = 10;return 0;}
This example results in the following output:
Maximum allowed attempts: 5
In this example, max_attempts
is declared as a constant integer. Attempting to modify it later in the code would result in a compilation error, ensuring that its value remains consistent.
Codebyte Example
All contributors
- Anonymous contributor
Contribute to Docs
- Learn more about how to get involved.
- Edit this page on GitHub to fix an error or make an improvement.
- Submit feedback to let us know how we can improve Docs.
Learn C++ on Codecademy
- Career path
Computer Science
Looking for an introduction to the theory behind programming? Master Python while learning data structures, algorithms, and more!Includes 6 CoursesWith Professional CertificationBeginner Friendly75 hours - Free course
Learn C++
Learn C++ — a versatile programming language that’s important for developing software, games, databases, and more.Beginner Friendly11 hours