Operators Revisited – Hierarchy of Operators, NOT and Conditional Operator in C

Today we will re-visit the operators once again. In the tutorial of logical operators deliberately missed the NOT operator.

Why? Ah… it’s a bit confusing and I don’t want to ruin the next important topics due to that operator.

NOT Operator (!)

The NOT operator (!) is used to reverse the results. This operator is mainly used as a key in big complex programs. By using this operator we can reverse the condition easily. Lets try to understand it with an example.

If ( !(y>6) )

In the above statement I am writing a condition that y should be lesser than or equal to 6. I can also write the same condition as

If (y<=6)

Both the statements will give the same results. You can use anyone of them.

Hierarchy of Operators

I have given the hierarchy of operators after arithmetic operators. Now we have learnt about the logical operators (AND OR NOT) too. So the new hierarchy of operators is given below.

Hierarchy of Operators

Conditional Operators

They are also called ternary operators. As we have to use three arguments to use this operator.

General form of Conditional/Ternary operator

(Expression 1 ? expression 2 : expression 3)

It is generally used to avoid small if-else statement. Remember it is not the alternative of if-else clauses. It can used at some places.

Lets try to understand it with some simple example.

if (x==10)

In the above we are basically checking if x is equal to 10. If condition turns true then it will assign y as 3. Otherwise it will assign y as 9. The same task can be completed using ternary operator.

Y=(x==10 ? 3 : 9);

I hope everyone will agree with the fact that above example is very much compact than the earlier version.

Another example to use ternary operators is given below.

( x > 4 ? printf ( “Value is greater than 4” ) : printf ( “Value is less than 4” ) ) ;

Nested Conditional Operator

Well nested conditional operators are used very rarely but they are good to make the program compact.
A small example of nested ternary operator is given below

Small = ( x < y ? ( x > z ? 9: 10 ) : ( y > z ? 14: 16 ) ) ;

In the above example small is the variable and it will store

9 if x<y and x>z
10 if x<y and x<z
14 if x>y and y>z
16 if x>y and y<z

Sounds confusing? Well that’s why they are used rarely. But like our example, it can sometimes make the program compact.

So that’s all for decision control instructions. I recommend you to make programs and practice for at least 2 days before proceeding further. In the next tutorial I will cover an overview to loops in C programming.

Leave a Comment

Your email address will not be published. Required fields are marked *