Saturday, September 21, 2019

c++ - Definition of variable inside loop

The difference is in terms of scope of the variable.


In the first case, once the while loop ends, the variable k cannot be accessed.


In the second case, the variable k can be accessed out of the while loop.


In both cases, the variable is defined on the stack (or as TartanLlama points out, they could be allocated in registers) and so there is no difference in terms of performance.


However, the example you've used is wrong in the case that the while loop will never end. I'm guessing this is just a piece of dummy code to explain the situation.

No comments:

Post a Comment

hard drive - Leaving bad sectors in unformatted partition?

Laptop was acting really weird, and copy and seek times were really slow, so I decided to scan the hard drive surface. I have a couple hundr...