-5

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?

3 Answers3

3

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.

therainmaker
  • 4,253
  • 1
  • 22
  • 41
3

This depends on your logic. If you need the variable outside the loop (e.g., to check the value after the loop) then you will have to define it outside the loop; if it is used only inside the loop, then you can define it only internally.

From an allocation point of view, in both cases the variable is likely allocated on the stack (even if in some cases the compiler may choose to use registers), and therefore there are no differences on performance.

Claudio
  • 10,614
  • 4
  • 31
  • 71
2

Normally variable is declared closest to where it is used. If the variable is only used inside the loop, then declare it inside the loop.

artm
  • 17,291
  • 6
  • 38
  • 54