Reputation: 87
First syntax
int i;
for(i=0;i<5;i++)
{
printf("Hello");
}
Second syntax
for(int i=0;i<5;i++)
{
printf("Hello");
}
I ask my professor he said both are same but I am not satisfied with this answer.
Please tell whether he was correct or not ?
is both syntax are same or different in some aspect?
Upvotes: 2
Views: 179
Reputation: 47933
To illustrate how the cases can be different: Suppose you have an array, and you are looking to find a certain element in it. You might write code like this:
#include <stdio.h>
int array[10] = {12, 34, 56, 77, 89, 123, 456, 789, 1001, 2002};
int main()
{
int i;
for(i = 0; i < 10; i++) {
if(array[i] == 77)
break;
}
if(i < 10)
printf("found it at index %d\n", i);
else
printf("not found\n");
}
But if you got rid of the int i;
line and changed it to
for(int i = 0; i < 10; i++) {
you'd get an error, because now i
is not defined outside the loop. My compiler prints error: use of undeclared identifier 'i'
for the if(i >= 10)
line.
The code as I've written it is, arguably, mildly poor style, anyway. It's true that, if you decare i
outside the loop, it's available after the loop, and you can use it to know where you found the element you were searching for. But to detect whether you found it or not, you have to repeat the i < 10
test, which is awkward. Another way is to use a separate variable to keep track of where and if you found it:
int main()
{
int found = -1;
for(int i = 0; i < 10; i++) {
if(array[i] == 77) {
found = i;
break;
}
}
if(found >= 0)
printf("found it at index %d\n", found);
else
printf("not found\n");
}
Now you're not trying to use i
outside the loop, so there's no problem.
Upvotes: 3
Reputation: 3812
Both code snippets will produce the same output, but there is a difference in meaning.
In the first code snippet, the variable i
will continue to exist after the for-loop, whereas in the second code snippet, the scope of the variable i
is limited to the body of the for-loop.
Additionally, the second code snippet is not valid for versions of C before C99, as these did not allow the declaration of a variable inside of a for-statement.
It is generally preferred to limit the scope of variable as much as possible, as this results in simpler code.
Upvotes: 5
Reputation: 24726
The only difference is the scope and lifetime of the variable i
. In the second example, the scope and lifetime of the variable i
is limited to the for
loop. In the first example, both are limited to the block in which your pasted code appears (probably function scope).
Upvotes: 2
Reputation: 328
They both will do the same except #1 will define i
for the for
block and everything after it. The second one will only define i
inside the for
block and will destroy the variable once the for
block exits.
Upvotes: 2