Wednesday, 31 August 2016

c++ - Definition of variable inside loop




I was looking for an answer for my questions on many pages but I couldn't find it.



In this case we are defining variable and reinitialaze it in every loop:



while(1)
int k = 7;


In this case we are defining variable before the loop and reinitialaze it in every loop.




int k;
while(1)
k = 7;


There is any advantages or disadvantages of using both methods? Or maybe it don't make a difference?


Answer



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

c++ - Does curly brackets matter for empty constructor?

Those brackets declare an empty, inline constructor. In that case, with them, the constructor does exist, it merely does nothing more than t...