Why would a language NOT use Short-circuit evaluation?

后端 未结 18 1940
天涯浪人
天涯浪人 2020-12-03 09:42

Why would a language NOT use Short-circuit evaluation? Are there any benefits of not using it?

I see that it could lead to some performances issues... is that true?

18条回答
  •  Happy的楠姐
    2020-12-03 10:03

    Many answers have talked about side-effects. Here's a Python example without side-effects in which (in my opinion) short-circuiting improves readability.

    for i in range(len(myarray)):
      if myarray[i]>5 or (i>0 and myarray[i-1]>5):
        print "At index",i,"either arr[i] or arr[i-1] is big"
    

    The short-circuit ensures we don't try to access myarray[-1], which would raise an exception since Python arrays start at 0. The code could of course be written without short-circuits, e.g.

    for i in range(len(myarray)):
      if myarray[i]<=5: continue
      if i==0: continue
      if myarray[i-1]<=5: continue
      print "At index",i,...
    

    but I think the short-circuit version is more readable.

提交回复
热议问题