2

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?

Community
  • 1
  • 1
prehistoricpenguin
  • 6,130
  • 3
  • 25
  • 42

3 Answers3

3

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

Mike
  • 47,263
  • 29
  • 113
  • 177
1

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);
}
melpomene
  • 84,125
  • 8
  • 85
  • 148
-1

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

DuXeN0N
  • 1,577
  • 1
  • 14
  • 29
  • @prehistoricpenguin that would depend on his definition of what "pure" C is. The C99 spec has not been out very long when you measure against how long the C language has existed, and new features might not be considered to be pure. Indeed, based on Mike's answer, C99 isn't even the default in GCC yet. – mah Dec 21 '12 at 13:54
  • 2
    @mah Based on Mike's answer, C89 isn't even the default in GCC yet. Color me unimpressed. – melpomene Dec 21 '12 at 13:57