简体   繁体   中英

condition for loop c++ odd behavior

I have a problem concerning the scope of variables inside for loops in c++. I have a variable j that counts a certain condition as seen in the code below

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 (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. 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. 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.

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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