Home » » What happens if you try to change a const variable in C++?

What happens if you try to change a const variable in C++?

 In C++, if you try to change the value of a const variable, the compiler will generate an error at compile-time, preventing you from modifying the variable.

Here is an example:

arduino
#include <iostream> using namespace std; int main() { const int x = 5; x = 10; // This line will generate a compile-time error return 0; }

In this code, x is declared as a const variable with an initial value of 5. The line x = 10; tries to modify the value of x, which is not allowed since x is declared as const. When you try to compile this code, the compiler will generate an error message similar to the following:

lua
error: assignment of read-only variable 'x'

So, in short, attempting to change a const variable in C++ results in a compile-time error.

 
Created By I_Am_Akshay | Distributed By Bharat Engine