Search code examples
c++conditional-statementsternary

c++ why do i get errors when using ternary operator


So here's my code, and I just can't find what's wrong. I would very much appreciate any help!

  #include <iostream>
using namespace std;
int main()
{
    int x,I=2;

    for (x = 100 ; x <= 500; x++)
    {
        (x % 3 == 0 && x % 5 == 0)? (cout << x << endl) : (I = 2);
    }

    return 0;
}

errors:

enter image description here

Update: I know I could use if ,else but it just made me curios, btw this program is supposed to find all numbers divisible by 3 and 5 from 100 to 500. Also if I run

 #include <iostream>
using namespace std;
int main()
{
    int x,I=2;

    for (x = 100 ; x <= 500; x++)
    {
        ((x % 3 == 0) && (x % 5 == 0))? (cout << x << endl) : (cout<<"somthing");
    }

    return 0;
}

It works fine so I guess the problem was in the second expression, is there a way to replace it with something that does nothing(that was the intent of I=2)


Solution

  • The ternary operator is not an if-else. It's for doing something like this:

    int i = (3 < 4) ? 3 : 4;
    

    Please use if-else for this usage.