Multiple if () in one

It:

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

It can be replaced by:

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

But it can be replaced by:

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

? (Without parentheses)

And is there a difference between languages?

PS: The answers should not be based on these examples.

+4
source share
4 answers

Firstly, this is all invalid if they have side effects.

Two, only if X is idempotent, which is a fancy way of saying if X can be called twice unchanged a second time.

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

&& binds to the tiger than || so yes you can drop the guys around && in this context. Operator precedence rules, which, I believe, are valid for any language in which they exist, I do not know any counterexamples, and the languages โ€‹โ€‹you asked about follow operator precedence rules C.

+6
source

In accordance with this:

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

Almost everything takes precedence over || so yes, it should work anyway.

This should also be done for Java, and also why?

+1
source

Your first equivalence operator is incorrect, at least in C ++. it

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

can execute X more than once if more than one condition is met. In addition, the above is guaranteed to evaluate at least A , C , F and G Meanwhile it

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

guaranteed to execute X only once, and guaranteed to evaluate at least A

+1
source

Yes, it doesnโ€™t show much difference, because && has a higher priority than ||

0
source

All Articles