I'm studying coding test with web compiler and i have an incomprehensible problem.
Does this bracket makes difference?
if(i < waitLine)
{
if(bridge.update(truck_weights[i]))
i ;
}
else
bridge.update(0);
this one is ok.
if(i < waitLine)
if(bridge.update(truck_weights[i]))
i ;
else
bridge.update(0);
but when i try this, compiler returns over time error. what's difference of this two style? isn't that else phrase just follow with first if condition?
CodePudding user response:
This:
if(i < waitLine)
if(bridge.update(truck_weights[i]))
i ;
else
bridge.update(0);
is the same as this:
if(i < waitLine) {
if(bridge.update(truck_weights[i])) {
i ;
} else {
bridge.update(0);
}
}
Not:
if(i < waitLine)
{
if(bridge.update(truck_weights[i]))
i ;
}
else
{
bridge.update(0);
}
So, it's different; I can't say why that's a compiler error, but I'd imagine it has something to do with the surrounding code.
CodePudding user response:
In your first coding block, by adding brackets you tie the "else" expression to the first "if" expression. But in the second code block, without the brackets, you tie the "else" statement with the second "if" statement.
So my suggestion is: Ask yourself which "if" statement has to have an alternative (in other words the "else" statement) and then decide the proper syntax. It seems that "i >= waitlist" but you cannot run this line:
bridge.update(0);
But in the second code block, this line is not executed at all, so the run time error does not appear.