DEV Community

Kerimova_Manzura
Kerimova_Manzura

Posted on

C++ Constant

A constant is a constant. To declare constants in the C++ programming language, const using the helper keyword ( We declare this variable as immutable). A constant can only read (get) its value.

# include  <iostream>
 using  namespace std; int
 main () {
     const int n = 13 ;  // _the value of n is always equal to 13; _return 0 ; 
}
Enter fullscreen mode Exit fullscreen mode

Let's look at the impossible.

# include  <iostream>
 using  namespace std; int
 main () {
     const int n = 13 ;  // the value of n is always equal to 13 
    n = 15 ;  // error: n is read-only here 
    cout << n; return 0 ; 
}
Enter fullscreen mode Exit fullscreen mode

2nd line : the C++ compiler will not allow such a case where an attempt is made to change the variable. and will give you the above error screen. Be careful when declaring a constant because this identifier cannot be changed during program execution and you will get an error if you try to change it.

A variable of an optional type can be declared as a constant when declaring a constant.

#include <iostream> 
using  namespace  std ; int
 main () {
     const int age = 24 ;  // age (age) constant const string name = "MasterSherkulov" ;  // name (name) constant const bool is_developer = true ;  // is_developer (developer) constant const char is_char = 'M' ;  // is_char constant const float PI = 3.14 ; 
}

Enter fullscreen mode Exit fullscreen mode

Top comments (0)