Friday 27 January 2017

c - 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?


Answer



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;
}


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...