Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do C programmers often declare the "counter" variable outside the for loop condition:

Tags:

c

I am new to C, and I presume that it makes no difference no matter how one does it, but I've noticed that in most examples for loops in see are written like in the following example:

int i;
for(i = 0; i < 10; i++){
   //some code
}

Rather then how I've initially been introduced to for loops in Java:

for(int i = 0; i < 10; i++){
    //some code
}

Is there any reason behind this in C?

like image 849
Marko Avatar asked Jan 25 '18 23:01

Marko


People also ask

What is the purpose of counter variable for a loop?

A counter variable in Java is a special type of variable which is used in the loop to count the repetitions or to know about in which repetition we are in. In simple words, a counter variable is a variable that keeps track of the number of times a specific piece of code is executed.

Should I declare variable outside for loop?

If the variable is declared outside the loop, then it has the global scope as it can be used through-out the function and inside of the loop too. If the variable is declared inside the loop, then the scope is only valid inside the loop and if used outside the loop will give an error.

Does the counter variable in a for loop have a value outside the loop?

Declaring the counter variableYou can declare the counter variable outside of the for loop.

Can we declare a variable in for loop in C?

When you declare a variable inside a for loop, there is one important point to remember: the scope of that variable ends when the for statement does. (That is, the scope of the variable is limited to the for loop.) ...


1 Answers

  1. Old c standards didn't allow to declare variables in the for and thus many programmers are used to it, and others simply are restricted to pre C99(c99) standard.

    But young c programmers like myself would write for (int counter ..., often even constructs like

     for (int index = 0; string[index] != '\0'; ++index) ...
    
  2. Sometimes, it's just because the algorithm requries it. For instance if you need to know what the last value of index was in the example construct above. Which is a common way to traverse string characters.

like image 108
Iharob Al Asimi Avatar answered Sep 22 '22 07:09

Iharob Al Asimi