0

Firstly, I use Visual Studio 2015, and I have already configured the openMP environment.(I promise it's right).

#pragma omp parallel for
for(int i= 0; i < 10; i++)
    printf("%d ", i);
printf("\n");

the codes above will fail,but if I modify a litte like this:

int i;
#pragma omp parallel for
for(i= 0; i < 10; i++)
    printf("%d ", i);
printf("\n");

the program will run correctly.

what'a more, when I use C++(modify the first codes as .cpp), the program can alse run normally.

why does this happen??

yazoo
  • 11
  • 3

1 Answers1

4

To declare variables inside the first clause of a for loop, you must either use a C++ compiler or a C compiler which isn't older than 17 years. Before the year 1999, you couldn't declare variables inside a loop in C.

Visual Studio set as C compiler is only somewhat compliant with a 26 years old C standard. It is not compliant with the current nor with the previous C standard from 1999.

Solve this by using a modern C compiler instead.

Lundin
  • 195,001
  • 40
  • 254
  • 396
  • 1
    Not exactly. You can declare local variables inside a loop (first instructions immediately after the `{` opening a block). Simply the loop variable must have been declared before the loop. Said differently `for (int i=...)` is rejected as a syntactic error. And Visual Studio syntax is not that old... do you remember the original K&R one? :-) – Serge Ballesta Mar 16 '16 at 12:21
  • @SergeBallesta Obviously I refer to the OPs code. But I can clarify the answer. A compiler that has not been updated even to a 17 year old standard is terribly old. – Lundin Mar 16 '16 at 13:28
  • I think technically it's called a [loop initial declaration (at least that's what GCC calls it)](http://stackoverflow.com/q/23229872/2542702). – Z boson Mar 16 '16 at 13:44
  • 1
    @Zboson No, it is technically called _clause-1_ or _clause-1 declaration_, see 6.8.5.3. – Lundin Mar 16 '16 at 13:53
  • @SergeBallesta, was the K&R syntax in this particularity case any different? – Z boson Mar 16 '16 at 13:55