Infinite for loop using continue

527 Views Asked by At

I'm writing a code that will run through each bin in a histogram and check if there are any non zero bins. If there are, it throws out an error message. My issue is, I want it to skip a bin because this bin should not be empty, but check all the other bins.

Only thing is this is creating an infinite loop. Here's my code

Int_t y;

for (int i = 0; i <= 100; i++) {
    y = hist - > GetBinContent(i)

    if (i = 1) continue;
    else if (y != 0) {
        std: cout << * * * * * ERROR * * * * * << std: endl;
        break;
    }

}

What's happening is it evaluates it for i = 0, skips i = 1, and then hits i = 2 and just continually evaluates that over and over again. If I take out the "if (i=1) continue;" line then it works.

Any ideas?

2

There are 2 best solutions below

0
On BEST ANSWER

Try this

if (i==1) continue;

i=1 mean you assign 1 to i. = means assign and == mean comparing .

In your code the value of i will always be 1 as you are using i=1

0
On

When you have errors with loops, it sometimes helps to run it in debug mode with a breakpoint in the loop or to put a print statement inside. Your error comes from the line: if (i=1) continue; . The segment i=1 sets i to be one and returns the value of i, which is interpreted as true (since it is non-zero). Then it goes to the next iteration, where it will once again set i to one. What you likely meant was if (i==1) continue; . This performs the comparison operator, which is what you intended.