Search code examples
c++cfor-loopparallel-processingopenmp

How to get rid of initialization after first of two for-loops?


I have a for loop that is currently in the form

for (i=0; i<N; i++) {
   y = 0.;
   for (j=0; j<N; j++)
      y += ...
}

And I'd like to rewrite it as

for (i=0; i<N; i++) {
   for (j=0; j<N; j++)
      y += ...
}

Where y is initialized at some prior point such that the two for loops are collapsed. Is there any way to accomplish this? This is an exercise from Section 16.4 of the following OpenMP tutorial


Solution

  • This is not the same as the code that you've linked to. The original has y indexed, i.e., it is an array:

    for (i=0; i<N; i++) {
       y[i] = 0.;
       for (j=0; j<N; j++)
          y[i] += ...
    }
    

    This could be rewritten as:

    for (i=0; i<N; i++)
      y[i] = 0.;
    
    for (i=0; i<N; i++)
      for (j=0; j<N; j++)
        y[i] += ...
    }
    

    In your case, y is scalar. Each iteration of the outer loop resets its value to 0 before the inner loop. If there are no side effects in the inner loop, only the last iteration of the outer one counts and you can simply get rid of it:

    i = N-1;
    y = 0.;
    for (j=0; j<N; j++)
      y += ...