3

Why does openmp give me this error :-

error: for statement expected before ‘{’ token

#include <stdio.h>
#include <stdlib.h>
#include <omp.h>
#include <unistd.h>

int main (int argc, char *argv[]) 
{

#pragma omp parallel 
{

int a[100],b[100],c[100];
int i =0;

    for(; i < 100; i++){
    a[i] = i;
    b[i] = i;
    }

    #pragma omp parallel for schedule(static,5)
    {
    int i = 0;
        for( ; i < 100 ; i++){ // this is the for loop that is referred in the error message
    c[i] = a[i] + b[i];
    }

    }

}

printf("Outside parallel block \n");

}

3 Answers 3

6

First, the second OpenMP pragma shouldn't have a "parallel" in it; you've already opened a parallel block, you just now need to share the work of the for loop.

Second, you can't have the parallel for enclose a general block; it has to be a for loop. If you really want a different i than is used above, do:

#pragma omp for schedule(static,5)
for (int i=0; i < 100; i++)
{
    c[i] = a[i] + b[i];
}
Sign up to request clarification or add additional context in comments.

Comments

3

This is an answer I posted to this question before I realised it is a duplicate of this one. As it somehow expands on the answers already given here, I'm reposing it.

parallel for is a combined directive. It combines parallel and for in a single directive, which allows for some space saving.

#pragma omp parallel for shared(sum) private(i,j,k)
...

is basically a shorthand notation for

#pragma omp parallel shared(sum) private(i,j,k)
{
   #pragma omp for
   ...
}

(the private clause could also be attributed to the for directive)

Since the syntax of the for directive requires that it is immediately followed by a for-loop, the same syntax requirement applies to the parallel for directive. In other words, the ... above can only be a for-loop with its associated (block) body:

#pragma omp parallel for ...
for (...)
{
   ...
}

Having the for-loop inside a block is erroneous. Having the entire parallel region inside a block is not though. The following is a perfectly valid syntax:

{
   #pragma omp parallel for ...
   for (...)
   {
      ...
   }
}

Comments

1

Do so

int i;
#pragma omp parallel for schedule(static,5)
for (i=0;...

2 Comments

I have been thinking about this. My concern is, if 'i' becomes a shared variable for different threads (instead of individual to each thread). Will the result be erratic due to different threads writing on the same variable?
@julianromera Yes. This answer needs to also state private(i) in order to be correct.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.