What are constants in C++?

C++Object Oriented ProgrammingProgramming

A constant in C++ is a variable/named value that you just want to assign a value to it once and never let it change again in the execution of that program. For example, if you're writing an application that uses the value of pi in a variable PI. You would never want to let this value change. Declaring this value as a const will prevent it's reassigning throughout the program.

You can define constants in C++ by adding the const qualifier before the declaration of the variable. 


using namespace std;
int main() {
   const int x = 9;
   x = 0;
   return 0;

This will define the constant variable x. But it will throw an error as we are trying to rewrite the value of a constant.

Updated on 11-Feb-2020 08:07:31