Logical operators in C

Relational operators are good at comparing two quantities. However, relational operators does not support comparison of three or more quantities.

For example, suppose you need to check range of a number. You need to check whether a number n is in between 1-100 or not. For that you must check two conditions, first check if n > 1 finally check if n < 100.

We use logical operators to combine two or more relational expressions as a single relational expression. Logical operators evaluates a Boolean value (integer in case of C) depending upon the operator used.

C supports three logical operators.

&&Logical AND
||Logical OR
!Logical NOT

Logical AND && operator

Logical AND && is a binary operator. It combines two relational expressions and evaluates 1 (true) if both the expressions are true otherwise 0 (false).

We use logical AND operator in situations when two or more conditions must be true for a decision. For example, “He is eligible for job, if he knows C and he has an experience of more than 2 years”. We can write the above statement programmatically as –

if (skill == ‘C’ && experience >= 2)
    //He is eligible for job

Note: Don't confuse logical AND & with bitwise AND &.

Logical OR || operator

Logical OR || is also a binary operator. Logical OR operator is used in situations, when a decision is to be taken if any of two conditions is satisfied.

It evaluates to 1 (true) if any of the two expressions is true otherwise evaluates to 0 (false). Logical OR operators are useful when either of the two relational expressions needs to be true. For example – consider the statement “It is weekend, if it is Saturday or Sunday”. We can write the given statement programmatically as -

if(today == Saturday || today == Sunday)
    // It is weekend

Note: Don't confuse logical OR || with bitwise OR |.

Logical NOT ! operator

Logical NOT ! is a unary operator that takes single operand and evaluates complement of its operand expression. It evaluates to 1 (true) if the operand is 0 (false) otherwise evaluates to 0 (false).

Let us take an example to understand - consider the statement "A person can register to my website, if he is not registered yet". Programmatic representation of the given statement is -

    // Register the person

About Pankaj

Pankaj Prakash is the founder, editor and blogger at Codeforwin. He loves to learn new techs and write programming articles especially for beginners. He works at Vasudhaika Software Sols as a Software Design Engineer and manages Codeforwin. In short Pankaj is Web developer, Blogger, Learner, Tech and Music lover.

Follow on: Facebook | Twitter | Google | or

Comments and discussion
Have a doubt, write here. I will help my best.
Before commenting you must escape your source code before commenting. Paste your source code inside
<pre><code> ----Your Source Code---- </code></pre>