Possible Duplicate:
C: for loop int initial declaration
Can we declare some variables in for
statement in C programming?If so,in which version of c standard will we find the feature?
Possible Duplicate:
C: for loop int initial declaration
Can we declare some variables in for
statement in C programming?If so,in which version of c standard will we find the feature?
Yes, you can do that starting with the c99 standard. A straight compile of the code:
int main()
{
for(int i = 0; i<10; i++)
printf("%d\n", i);
return 0;
}
with (the default "gnu89") gcc
would give you the answer:
In function
main
:
error: 'for' loop initial declarations are only allowed in C99 mode
note: use option -std=c99 or -std=gnu99 to compile your code
In C89/C90, all declarations have to appear at the beginning of a block:
/* valid in C89/C90 */
printf("Hello\n");
{
int i;
for (i = 0; i < 10; i++) {
int j = i % 3;
printf("%d\n", j);
}
}
Starting with C99 you can mix declarations and statements, and declare variables in the first part of a for
:
/* valid in C99 */
printf("Hello\n");
int whatever;
for (int i = 0; i < 10; i++) {
int j = i % 3;
printf("%d\n", j);
}
In pure C you can't declare variables in for
statement. This feature available only in C++.
In C all the variables must be declared at the beginning of the code block