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

Image of Datadog

Master Mobile Monitoring for iOS Apps

Monitor your app’s health with real-time insights into crash-free rates, start times, and more. Optimize performance and prevent user churn by addressing critical issues like app hangs, and ANRs. Learn how to keep your iOS app running smoothly across all devices by downloading this eBook.

Get The eBook

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more