logical and relational operators in C

Hello coders! Welcome back!

 Previously we looked into Arthematic operators (click here  to read) and increment and decrement operator (click  here to read)

Today will look into another operator in C. That is logical and relational operators.

Logical operator-


&& and || are used to combine two conditions.

➝&& operator results True when all conditions are satisfied and False when either of the condition fails to satisfy.
let's look into the code-

Here in this code if and else statements are used to check the condition. When the condition satisfies it execute the following block of codes. If the condition fails it execute 'else' block of statements.
Both the conditions are satisfied hence it prints "code_with_me18".
let's check what happens when one of the conditions fails.

Now the second condition fails hence it execute else statements and print 'exit'.

⟶ || operator results True when either of the condition satisfies and False when all the conditions fail to satisfy.

Here the same example is taken as above. The second condition fails to satisfy even then it prints the 'if' statement block of codes.

⟶ ! operator is used for complementing an operator. It changes a True condition into False 
And False condition into True. 

Here in this code the condition (a<b) is false using NOT operator we turned it to true and printed the following statements.

Short-circuit in logical operator 

  1. && short circuit in logical operator- 
If one expression in condition results 'false' then consecutive expression is not evaluated. 
Let's look with an example of code-

Here the first condition is false(means 0) hence according to short circuit the next condition is not evaluated. Hence 'b' is not incremented.

Here both the condition satisfy hence first it returns true(means 1) then increment the value of 'b'.

               2. || short circuit in logical operator- 

If one expression in a condition fails to satisfy, even then the consecutive expressions are evaluated. let's take the same example-

Here the first condition fails to satisfy and the second condition gets evaluated and produces 'true', according to OR operator if one condition satisfies then it gives true. Then the value of 'b' gets incremented.

It gives 'false' when both the expression fails to satisfy.

Relational operator-

Relational operators are used in comparing the value.
This is it for this blog will look into other types of the operator in an upcoming blog. If any doubts till here drop a comment always ready to clear them. 

Happy learning!

Comments

Popular post