C - Operator Logical Operator

AND Operator &&

The logical AND operator, &&, is a binary operator that combines two logical expressions.

Two expressions that evaluate to true or false. Consider this expression:

test1 && test2

This expression evaluates to true if both expressions test1 and test2 evaluate to true.

If either or both of the operands are false, the result of the operation is false.

Here's an example:

if(age > 12 && age < 20)
  printf("You are officially a teenager.");

The printf() statement will be executed only if age has a value from 13 to 19 inclusive.

The operands of the && operator can be bool variables. You could replace the previous statement with the following:

bool test1 = age > 12;
bool test2 = age < 20;
if(test1 && test2)
  printf("You are officially a teenager.");

OR Operator ||

OR operator, ||, checkes for any of two or more conditions being true.

If either or both operands of the || operator are true, the result is true.

The result is false only when both operands are false. Here's an example of using this operator:

if(a < 10 || b > c || c > 50)
  printf("At least one of the conditions is true.");

The printf() will be executed only if at least one of the three conditions, a<10, b>c, or c>50, is true.

You can use the && and || logical operators in combination:

if((age > 12 && age < 20) || rate > 5)
  printf ("Either you're a teenager, or you're gamer, or possibly both.");

You could replace the previous statement with the following:

bool over_12 = age > 12;
bool undere_20 = age < 20;
bool age_check = over_12 && under_20;
bool rate_check = rate > 5000;
if(age_check || rate_check)
 printf ("Either you're a teenager, or you're rich, or possibly both.");

You could define the value of age_check in a single step, like this:
bool age_check = age > 12 && age < 20;
bool rate_check = rate > 5000;
if(age_check || rate_check)
 printf ("Either you're a teenager, or you're rich, or possibly both.");

NOT Operator !

NOT operator, represented by !.

The ! operator is a unary operator, because it applies to just one operand.

The logical NOT operator reverses the value of a logical expression: true becomes false, and false becomes true.

Quiz

Example