2

Code:

void Test()
{
    float dt = 0.3;
    float playTime = 1;
    while ( playTime > 0.0 )
    {
      const float delta = std::min( playTime, dt );
      std::cout << delta << std::endl;
      playTime -= delta;
    }
}

Result:

0.3
0.3
0.3
0.1

In c++, const keyword means doesn't change. So, we use the keyword const to make vars constant.

But in this case,
Why const var, delta can be changed every time being called?

Since, while loop start new code block(in stack area),
So, I think variable, delta exist already for while looping execution.


Jinbom Heo
  • 7,248
  • 14
  • 52
  • 59

2 Answers2

4

Because you get a new variable with every iteration of the loop.

The scope of the variable delta is restricted to the body of the loop. That means it will be destroyed and re-created with every iteration. The const simply means that its value cannot change while its alive, but since you recreate it with every iteration, its value may indeed change between iterations, just never within the course of a single iteration.

Note that it is possible in C++ to declare a variable in a way that it persists throughout the lifetime of a program, even if its scope is left. That is what the static keyword is for. Change your delta declaration to static const float delta = std::min( playTime, dt ); and it will retain the same value throughout.

In this particular case though, it's probably better to just move the declaration before the loop, as static will also persist the variable through multiple calls to the function Test.

ComicSansMS
  • 51,484
  • 14
  • 155
  • 166
3

The scope of delta is the block of the while loop. It comes to life at the start of it, and dies at the end. That happens every time the block is entered and exited, i.e. every iteration.

The const qualifier only means you cannot modify it while it's alive. It doesn't change the extent of its lifetime. In essence, it's a "different" delta each time the block is executed.

If you want it to be fixed for each and every iteration, you must move it to an enclosing scope (such as the function body), and initialize is there.

StoryTeller - Unslander Monica
  • 165,132
  • 21
  • 377
  • 458