Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does It Matter If I Declare A Variable Inside A Loop?

My question is that does it matter if I declare a variable outside the loop and reinitialize every time inside the loop or declaring and initializing inside the loop? So basically is there any difference between these two syntaxes (Performance,standard etc)?

Method 1

int a,count=0;
while(count<10)
   a=0;

Method 2

int count=0;
while(count<10)
   int a=0;

Please assume that this is only a part of a bigger program and that the body inside loop requires that the variable a have a value of 0 every time. So, will there be any difference in the execution times in both the methods?

like image 252
Pranav Jituri Avatar asked Jun 11 '26 08:06

Pranav Jituri


1 Answers

Yes, it does matter. In second case

int count=0;
while(count<10)
   int a=0;

a can't be referenced out side of while loop. It has block scope; the portion of the program text in which the variable can be referenced.
Another thing that Jonathan Leffler pointed out in his answer is both of these loops are infinite loop. And second, the most important second snippet would not compile without {} (in C) because a variable definition/declaration is not a statement and cannot appear as the body of a loop.

 int count  =0;
 while(count++ < 10)
 {  
      int a=0;  
 } 
like image 72
haccks Avatar answered Jun 13 '26 01:06

haccks



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!