Page 1 of 1
if() inconsistency
Posted: 24 Nov 2019 08:06
by jassing
This should be valid, but it's not.
if (true) a=1;
else a=2;
The following is valid. Only the if requires brackets,
if (true) {a=1;}
else a=2;
the else doesn't require them, and that's the inconsistent part.
Re: if() inconsistency
Posted: 24 Nov 2019 09:08
by Desmanto
else can have them too.
Or to be exactly clear, I always put indent
Code: Select all
if(true)
{
a = 1;
}
else
{
a = 2;
}
But that takes a looooot of space for a simple if-else like that. The else part doesn't have to have the braces if it is single lines. The same with the if() part, if you don't put semicolon at the first. The else part still require semicolon though to end the if-else block.
So the braces only used to group multiple expression into single block of execution.
You can even simplify it as single line, if you already understand what it does and want to save some space
Heck, you even use ternary form here, if the if-else part assign value to the same variable
Re: if() inconsistency
Posted: 25 Nov 2019 05:20
by jassing
The point is if() requires the brackets, while the else does not.
Re: if() inconsistency
Posted: 25 Nov 2019 17:06
by Desmanto
Oh, the bracket is requirement for the if() block. Else is optional, hence not bracketed.