Search code examples
c++cconstantslifetimeobject-lifetime

Why can I reinitialize a constant inside a loop?


The compiler throws no warnings or errors for the following code. Is the meaning of the const qualifier being abused? Obviously I cannot reassign it later in the same loop iteration but it does seem to reassign it after each iteration.

Sample code:

for(int i = 0; i < 10; ++i)
{
  const int constant = i;
}

Solution

  • You aren't re-initializing it, you're just initializing it in each loop iteration*. Formally there is a new int being created and destroyed in each loop iteration, although the compiler can do whatever it wants as long as it seems to behave that way.


    * You can't really "re-initialize" things in C++, initialization only happens once in the lifetime of an object