if() inconsistency

Post your questions and help other users.

Moderator: Martin

Post Reply
User avatar
jassing
Posts: 94
Joined: 16 Jul 2017 01:42
Location: SF Bay Area

if() inconsistency

Post by jassing » 24 Nov 2019 08:06

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.

User avatar
Desmanto
Posts: 2709
Joined: 21 Jul 2017 17:50

Re: if() inconsistency

Post by Desmanto » 24 Nov 2019 09:08

else can have them too.

Code: Select all

if (true) {a=1;}
else {a=2};
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.

Code: Select all

if(true)
  a = 1
else
  a = 2;
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

Code: Select all

if(true) a = 1 else a = 2;
Heck, you even use ternary form here, if the if-else part assign value to the same variable

Code: Select all

a = if(true) 1 else 2;
Index of Automagic useful thread List of my other useful posts (and others')
Xiaomi Redmi Note 5 (whyred), AOSP Extended v6.7 build 20200310 Official, Android Pie 9.0, Rooted.

User avatar
jassing
Posts: 94
Joined: 16 Jul 2017 01:42
Location: SF Bay Area

Re: if() inconsistency

Post by jassing » 25 Nov 2019 05:20

The point is if() requires the brackets, while the else does not.

User avatar
Desmanto
Posts: 2709
Joined: 21 Jul 2017 17:50

Re: if() inconsistency

Post by Desmanto » 25 Nov 2019 17:06

Oh, the bracket is requirement for the if() block. Else is optional, hence not bracketed.
Index of Automagic useful thread List of my other useful posts (and others')
Xiaomi Redmi Note 5 (whyred), AOSP Extended v6.7 build 20200310 Official, Android Pie 9.0, Rooted.

Post Reply