elses chain if blocks together, is why.
fixing the error, and then more explains..
if(y == 0)
cout << "error\n";
else if(x % y == 0)
cout << "ok";
above, if its zero, you will not try to do the % operation which would throw an error. This is because, if y is zero, it does not go into the else at all. The else only happens when the if(y==0) is false.
removing the else, it WILL go into the % and crash:
if(y == 0)
cout << "error\n"; //the if y == 0 block is DONE and FORGOTTEN.
-------------------------
if(x % y == 0) //its as if the above did not exist. it now tries x%0 and explodes.
cout << "not ok";
one thing to note:
if is a statement, and can produce a compound statement (multiple lines treated as one statement) with {} around it.
else is also a compound statement that can have one or more statements inside it.
else if(something) is NOT a thing, not really. Its a pretty way to write two statements on one line, and its common to see it, but this is really, to the computer, shaped like the following:
1 2 3 4 5 6 7 8 9 10 11
|
if(something)
{
statement; //for you, the cout
statement2; //and not present in your code, you only had 1 statement, ok
}
else //and it so happens in your example that
//statement 3 is an if statement and statement 4 is the cout
{
statement3;
statement4;
}
|
many folks claim best practice is to always use {} even for one line compound statements. That way it is clear what is going on in these kinds of blocks and its less error prone if you edit it later and inject another statement that should be in {} but oops.