Course List http://www.c-jump.com/bcc/

C++ Operators


  1. Arithmetic Operators
  2. Integer Division
  3. Modulus Operator
  4. Relational Operators
  5. More Relational Operators
  6. Operator Associativity
  7. Arithmetic If
  8. Assignment Operators
  9. Increment and Decrement Operators
  10. Logical AND, logical OR operators
  11. Logical operators short-circuiting

1. Arithmetic Operators



2. Integer Division



3. Modulus Operator



4. Relational Operators



5. More Relational Operators



6. Operator Associativity



7. Arithmetic If



8. Assignment Operators



9. Increment and Decrement Operators

  • Shortcuts to add or subtract 1:

    
        ++i; // add one to i 
        --j; // subtract one from j 
    
    
  • Related topics:

    • (++) and (--) are unary operators

    • side effects

    • always used with modifiable values

  •  

    
    int main()
    {
        int i = 0;
        int k = (i + 1); // No side effects
        int k = ++i; // Side effect: i incremented
        return 0;
    }
    
    

Logical AND, logical OR operators

  • The logical AND && operator returns 1 if both exp1 and exp2 are non-zero:


        if ( exp1 && exp2 ) {
            //...
        }

#include <cassert>
void main()
{
    int x = 1;
    int y = 2;
    // true: y > x
    // true: x > 0
    if ( y > x && x > 0 ) {
        assert( y > x );
        assert( x > 0 );
    }
}
  • The logical OR || operator returns 1 if either exp1, or exp2, or both are non-zero:


        if ( exp1 || exp2 ) {
            //...
        }

void main()
{
    int x = 1;
    int y = 2;
    if ( x == 1 || y == 2 ) {
        //...
    }
}

Logical operators short-circuiting

  • Expressions connected by && or || are evaluated left to right.

  • Evaluation stops as soon as the truth or falsehood of the result is known. This feature is known as short-circuiting.


void main()
{
    int x = 1;
    int y = 2;
    if ( x == y && y > 0 ) {
        // execution nevert gets here...
    }
    // expr y > 0 never evaluated!
    if ( x == 1 || y == 2 ) {
        // expr y == 2 never evaluated!
        // ...
    }
}