So far we have used only the logical operators && and ||. The third logical operator is the NOT operator, written as !. This operator reverses the result of the expression it operates on. For example, if the expression evaluates to a non-zero value, then applying ! operator to it results into a 0. Vice versa, if the expression evaluates to zero then on applying ! operator to it makes it 1, a non-zero value. The final result (after applying !) 0 or 1 is considered to be false or true respectively. Here is an example of the NOT operator applied to a relational expression.
! ( y < 10 )
! ( y < 10 )
This means “not y less than 10”. In other words, if y is less than 10, the expression will be false, since ( y < 10 ) is true. We can express the same condition as ( y >= 10 ).
The NOT operator is often used to reverse the logical value of a single variable, as in the expression
if ( ! flag )
This is another way of saying
if ( flag == 0 )
Does the NOT operator sound confusing? Avoid it if you want, as the same thing can be achieved without using the NOT operator.
if ( flag == 0 )
Does the NOT operator sound confusing? Avoid it if you want, as the same thing can be achieved without using the NOT operator.
No comments:
Post a Comment