简体   繁体   English

如何在两个 for 循环中的第一个之后摆脱初始化?

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

I have a for loop that is currently in the form我有一个当前处于以下形式的 for 循环

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.其中 y 在某个先前的点被初始化,使得两个 for 循环被折叠。 Is there any way to accomplish this?有什么办法可以做到这一点吗? This is an exercise from Section 16.4 of the following OpenMP tutorial这是来自以下 OpenMP 教程第 16.4 节的练习

This is not the same as the code that you've linked to.这与您链接到的代码不同。 The original has y indexed, ie, it is an array:原始有y索引,即,它是一个数组:

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.在您的情况下, y是标量。 Each iteration of the outer loop resets its value to 0 before the inner loop.外循环的每次迭代在内循环之前将其值重置为 0。 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 += ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM