What are constants in C++?


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. 

Example

#include<iostream>
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.

karthikeya Boyini
karthikeya Boyini

I love programming (: That's all I know

Updated on: 11-Feb-2020

400 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements