Search code examples
c++visual-studiocontinue

C++ ? operator with continue operator in for loop


I have a method which looks like this:

bool Perfect(int num) {
    int sum = 0;
    for (int i = 1; i < num; i++)
    {
        num%i == 0 ? sum += i : continue;
    }
    return sum == num ? true : false;
}

I'm trying to combine here ? operator with continue operator...

So logically if the statement here is false in this line:

num%i == 0 ? sum += i : continue;

I will just skip the iteration or do nothing?

If I do it like this the compiler reports an error like:

expected an expression

And in case like this:

num%i == 0 ? sum += i

It says:

Expected a ':'

Is there any way to use continue with ? operator or just simply avoid false case somehow ???


Solution

  • bool Perfect(int num) {
        int sum = 0;
        for (int i = 1; i < num; i++)
        {
            if(num % i == 0)
             sum += i;
        }
        return sum == num;
    }
    

    Use an if statement. No need of continue since you have no other statement after sum += i.