shen tao
shen tao

Reputation: 3

C++ Error when for loop is in if else statement when using OpenMP

When I am running the following code in visual studio 2015, I got the error on "else" statement that "expected a declaration". I can't figure out why this can't work since I have specified the parallel area.

void test(int a) {
    if (a % 2 == 0) {
        #pragma omp parallel{
        #pragma omp for
        for (int i = 0; i < 10; ++i) {
            cout << i;
        }
        }
    }
    else {
        //#pragma omp parallel for 
        for (int i = 0; i < 10; ++i) {
            cout << i;
        }
    }
}

Without the openMP declaration, the code runs well. Why it happens and how to solve it? Thanks a lot!

Upvotes: 0

Views: 392

Answers (2)

Josh Harold
Josh Harold

Reputation: 11

Your problem is cuased by an extra } which makes the else statement one } off from the if statement and the compilier does not know what to do with it

void test(int a) 
{
    if (a % 2 == 0) 
    {
        for (int i = 0; i < 10; ++i) {
            cout << i;
        }
        } //here is the extra }!
    }else 
    {
        for (int i = 0; i < 10; ++i) 
        {
            cout << i;
        }
    }
}

here is the code without the extra }

void test(int a) 
{
    if (a % 2 == 0) 
    {
        for (int i = 0; i < 10; ++i) {
            cout << i;
        }
    }else 
    {
        for (int i = 0; i < 10; ++i) 
        {
            cout << i;
        }
    }
}

Also I noticed that your formatting is a bit odd and it probably helped with you not noticing the extra }

Best of luck! :)

Upvotes: 1

Hariom Singh
Hariom Singh

Reputation: 3632

I think problem is your parenthesis {}

#include<iostream>
using namespace std;

void test(int a)
{
    if (a % 2 == 0)
    {
    #pragma omp parallel
    {
    #pragma omp for
        for (int i = 0; i < 10; ++i)
        {
            cout << i;
        }
    }
    }

else
{
    #pragma omp parallel for
    for (int i = 0; i < 10; ++i)
    {
        cout << i;
    }

 }
}

int main()
{
    test(3);
    return 0;
}

Result:

0123456789Program ended with exit code: 0

Upvotes: 0

Related Questions