简体   繁体   English

循环c ++奇怪行为的条件

[英]condition for loop c++ odd behavior

I have a problem concerning the scope of variables inside for loops in c++. 我有一个关于c ++中for循环内变量范围的问题。 I have a variable j that counts a certain condition as seen in the code below 我有一个变量j,它可以计算某些条件,如下面的代码所示

int j;
for (int i=0; i<8; i++){
    if ((betaSol(i,0) >= -HalfPi) && (betaSol(i,0) <= HalfPi)){
        // j gives size of new vector where beta is within bounds
        j++;
    }
}
Eigen::MatrixXd vectorname(j,1);

Now I want to use the same j in the condition of the next for loop as follows 现在我想在下一个for循环的条件下使用相同的j,如下所示

 for (int ii = 0; ii<j; ii++ ){
        vectorname(ii,0)  =  functionname(alphaSol_filt(ii,0),betaSol_filt(ii,0));
    }

Here is where the problem occurs. 这是发生问题的地方。 This becomes an infinite loop and ii goes out of bounds. 这将成为无限循环,并且ii会超出范围。 The strange thing is that when I replace the second loop with the following: 奇怪的是,当我用以下内容替换第二个循环时:

  for (int ii = 0; ii<j; ii++ ){
    std::cout << j <<std::endl;
  }

it does work correctly. 它确实可以正常工作。 However if I change anything, then it becomes an infinite loop and I do not know what happens 但是,如果我更改了任何内容,那么它将变成一个无限循环,并且我不知道会发生什么

When you have an empty initialization, j is initialized to whatever value happens to be in the memory space it is stored in, at least with most compilers I've used. 当您进行空初始化时,至少对于我使用过的大多数编译器,j都会初始化为存储在其存储空间中的任何值。 Since you increment j I assume you don't initialize it in the loop, so you'll probably need to put j = 0, or some other value that makes sense for your program. 由于您递增j,所以我假设您没有在循环中对其进行初始化,因此您可能需要将j = 0或其他对您的程序有意义的值放进去。

As for the second loop always looping, I have seen compilers set initialized ints with no value assigned to the maximum possible value for ints (2,147,483,647), which would take a very long time to loop through even with not much being done and would seem like an infinite loop. 至于第二个循环总是循环的,我看到编译器设置了初始化的int,而没有为int的最大可能值(2,147,483,647)分配任何值,即使没有做很多事情,循环也将花费很长时间,并且看起来无限循环

use : 采用 :

int j=0;

instead of 代替

int j;

and check if the functions within the for loop change the value of ii or j that makes the loop infinite. 并检查for循环中的函数是否更改了使循环无限的iij的值。

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

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