Cpp - Precedence of Boolean Operators

Introduction

The && operator has higher precedence than ||.

The precedence of both these operators is higher than the precedence of an assignment operator.

The !operator is a unary operator and thus has higher precedence.

Demo

#include <iostream> 
using namespace std; 
int main() /*from  ww  w.  jav  a  2 s . com*/
{ 
    cout << boolalpha; // Outputs boolean values 
                           // as true or false 
    bool res = false; 

    int y = 5; 
    res = 7 || (y = 0); 
    cout << "Result of (7 || (y = 0)): " << res 
          << endl; 
    cout << "Value of y: " << y << endl; 

    int  a, b, c; 

    a = b = c = 0; 
    res = ++a || ++b && ++c; 
    cout << '\n' 
          << "  res = " << res 
          << ",   a = " << a 
          << ",   b = " << b 
          << ",   c = " << c << endl; 

    a = b = c = 0; 
    res = ++a && ++b || ++c; 
    cout << "  res = " << res 
          << ",   a = " << a 
          << ",   b = " << b 
          << ",   c = " << c << endl; 
    return 0; 
}

Result

Related Topic