What's the difference between if (A) if (B) and if (A and B)?

if(A) then if(B)

against

if(A and B)

Which is the best to use and why?

+3


source to share


3 answers


Given:

if (a) {
  if (b) {
    /// E1
  }
  /// E2
} else {
  // E3
}

      

It might be tempting to replace it with:



if (a && b) {
 /// E1
} else {
 // E3
}

      

but they are not equivalent (a = true and b = false shows a counter argument for it)

Also, there is no reason not to link them if the language allows short-circuiting operations like AND, OR. And most of them allow it. The expressions are equivalent and you can use chaining to improve the readability of your code.

+5


source


It depends on your specific case, but usually:

1) if (A and B)

looks better / cleaner. It will immediately clear that the next block will be executed if the A

and tags are applied B

.

2) if(A) then if(B)

better when you want to do something, when applied A

, but B

not. In other words:



if (A):
    if (B):
        # something
    else:
        # something else

      

usually looks better than

if (A and B):
    # something
if (A and not B):
    # something else

      

+4


source


You noted this "algorithm" and "logic" and from that point of view I would say a little difference.

However, in practical programming languages, there may or may not be an issue of efficiency (or even feasibility).

Programming languages ​​such as C, C ++, and Java ensure that an expression A && B

is evaluated first A

, and if false is B

not evaluated. This can make a big difference if it B

is expensive compared to a calculator or invalid if it A

is false.

Consider the following piece of C code:

int*x
//....
if(x!=NULL&&(*x)>10) {
//...

      

Assessment (*x)

when x==NULL

very likely to result in a fatal error.

This "trick" (called short-circuit estimation) is useful because it avoids having to write a little more verbose:

if(x!=NULL){
  if((*x)>10){

      

Older versions of VB, such as VB6, are notorious for not making short circuits.

Another is that B

in A || B

will not be evaluated if A

true.

Support discussion:

Do all programming languages ​​have a boolean short circuit rating?

In any language that provides short-circuiting and has an optimizing compiler, you can assume that there is hardly any difference in code efficiency and go with the most readable ones. Usually it is if(A&&B)

.

+2


source







All Articles