简体   繁体   中英

C++: While Loop won't break

we just had an exercise at school and one part of it is to check, if a given EAN (European Article Number) is valid.

I wrote a function for it, but when I am using the while-loop, it won't go out of the loop. Here's the code:

bool checkEan13(unsigned int code[])
{
    int sum1 = 0;
    int sum2 = 0;
    int sum;

    for (int i = 0; i <= 10; i += 2)
    {
        sum1 += code[i];
    }

    for (int i = 1; i <= 11; i += 2)
    {
        sum2 += code[i];
    }

    sum2 *= 3;
    sum = sum1 + sum2;

    int difference;
    int nextNumber = sum;

    while (!nextNumber % 10 == 0)
    {
        nextNumber++;

        //if (nextNumber % 10 == 0)        <-- it works, when I put in this
        //{                                <--
        //  break;                         <--
        //}                                <--
    }

    difference = nextNumber - sum;

    if (difference == code[12])
    {
        return true;
    }
    else {
        return false;
    }
}

As you can see in the code, it works, when I do a check with an if-statement, but why does it not work without it? Shouldn't the statement of the while-loop be invaild, if "nextNumber" is eg 50?

Thanks!

This has to do with operator precedence . ! has a higher precedence then % so your condition is actually evaluated as

(!nextNumber) % 10 == 0

So if nextNumber is a non 0 value then (!nextNumber) if false or 0 and 0 % 10 is 0

To fix it you can use

!(nextNumber % 10 == 0)

Which will check if nextNumber % 10 is equal to 0 and return the opposite of that check.

Of course as Marc van Leeuwen pointed out we could simply write

nextNumber % 10 != 0

which does the exact same things and now we no longer have to worry about the operator precedence.

Please read about operator precedence. Try with while (!((nextNumber%10)==0)) .

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