Const prefix Definition

This is my first time of C++. And as far as I could understand, const prefix means the next:

Const prefix marks the variable’s value as readonly variable. That means once you declare the variable with the const prefix, you cannot modify its value in any line of code. Below or even some cases, above.

E.g:
If you put:

1| int a = 4;
2| int b = 3;
3|
4| a = 12;
5|
6| std::cout << a + b;

Compiler will work.
But if you put, by e.g:

1| const int a = 4;
2| int b = 3;
3|
4| a = 12;
5|
6| std::cout << a + b;

Compiler will fail. Because when you declared a const variable in the first line, compiler will understand that this variable must be used for read its value only, not for change it (as shown in the fourth line)

However, if you just put:

1| const int a = 4;
2| int b = 3;
3|
4| std::cout << a + b;

Compiler will work. Because const variable declared in the first line it’s also used in the fourth line but just for read it.

Maybe I’m wrong, but that’s all that for now I could understand :slight_smile:

1 Like

Privacy & Terms