Const

Hello. I am recently new to C++ and I was wondering what "const" does, and when I should use it. Thanks for answering!
const means constant value that can not change.

1
2
3
4
5
int a = 5;
a = a + 1;
//this ok because a is not const
const int b = 3;
b = b + 1; // this won't be allowed 
When you declare something const, the compiler will enforce that promise; prevent you from accidentally modifying constant objects.

On the other hand, if the compiler knows that something won't change, it could do more optimization.

See also: https://isocpp.org/wiki/faq/const-correctness
Topic archived. No new replies allowed.