Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple if() in one [closed]

This:

if (A || B) { X; }
if (C && D) { X; }
if (F != G && H + I === J) { X; }

Can be replaced by:

if ((A || B) || (C && D) || (F != G && H + I === J)) { X; }

But can it be replaced by:

if (A || B || C && D || F != G && H + I === J) { X; }

? (Without parentheses)

And is there any difference between languages?

P.S: The answers shouldn't based on those examples.

like image 966
Mageek Avatar asked Feb 19 '23 14:02

Mageek


1 Answers

One, this is all invalid if these have side-effects.

Two, only if X is idempotent, which is a fancy way of saying, if X can be called twice with no change on the second time.

http://en.cppreference.com/w/cpp/language/operator_precedence

&& binds tigther than ||, so yes, you may drop parens around && in this context. The operator precedence rules I believe hold valid for any language that has them, I don't know any counterexamples to this, and the languages you asked about do follow C operator precedence rules.

like image 72
djechlin Avatar answered Mar 02 '23 13:03

djechlin