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?
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.
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.
Declaring the counter variableYou can declare the counter variable outside of the for loop.
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.) ...
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) ...
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With