Search code examples
c++comparisonshort-circuiting

Are the integer comparison operators short circuited in C++?


Like the title states, are the integer (or any numerical datatypes like float etc.) comparison operators (==, !=, >, >=, <, <=) short circuited in C++?


Solution

  • They can't short circuit. To know if x == y, x != y, etc are true or false you need to evaluate both, x and y. Short circuiting refers to logical boolean operators && and ||. Logical AND is known to be false if the first argument is false and Logical OR is known to be true if the first argument is true. In these cases you don't need to evaluate the second argument, this is called short circuiting.

    Edit: this follows the discussions for why x >= y don't short circuit when the operands are unsigned ints and x is zero:

    For logical operands short circuiting comes for free and is implementation neutral. The machine code for if(f() && g()) stmt; is likely to look similar to this:

    call f
    test return value of f
    jump to next on zero
    call g
    test return value of g
    jump to next on zero
    execute stmt
    next: ...
    

    To prevent short circuiting you actually need to do the computation of the result of the operator and test it after that. This takes you a register and makes the code less efficient.

    For non-logical operators the situation is the opposite. Mandating short circuiting implies:

    • The compiler can't choose an evaluation of the expression that uses a minimum number of registers.
    • The semantics may be implementation defined (or even undefined) for many cases, like when comparing with maximum value.
    • The compiler needs to add an additional test/jump. For if(f() > g()) stmt; the machine code will look like this:

      call f
      mov return value of f to R1
      test return value of f
      jump to next on zero
      call g
      compare R1 with return value of g
      jump to next on less-than equal
      execute stmt
      next: ...
      

      Note how the first test and jump are just unnecessary otherwise.