The numbers and variables used can be of any integer or floating data type. In the examples below either "b" or "a" can also be a number, like 5 or 7.2 .
a > b (a greater b) a >= b (a greater or equal to b) a == b (a equal to b ) a != b (a not equal to b) a < b (a less than b) a <= b (a less than or equal to b)IMPORTANT : A common mistake is to write a=b instead of a == b. That is fine as far as the C++ language is concerned. Your program though will take two actions you did not want it to do :
Often, the comparison of two numbers/ variables is not enough. For example if you wish to test whether a certain variable has a value falling inside an interval of known limits.
1 < n && n < 100
In the above example two separate conditions are tested and only if both of them evaluate separately to true the entire expression evaluates to true. In this case, if "n" is somewhere inbetween 1 and 100.
In general :
expression1 && expression2 ...... && expressionX
evaluates to true only if each of "expression1" ... evaluates to true.
The next example involves the OR operator. Here we test whether the value of a variable "n" falls outside a given interval :
n < 1 || n > 100
This entire expression evaluates to true if either n < 1 OR n > 100 is true. In general :expression1 || expression2 ...... || expressionX
evaluates to true if at least one of "expression1" ... evaluates to true.
In general, there are no restrictions from the point of view of the C++ programing language as to how many of each && and || appear in a given logical expression. Great care has to be taken though and the use of parenthesis is encouraged. Examples :
( a > 0 && b > 0 ) || c > 0 a > 0 && ( b > 0 || c > 0 )
The general rule is that the expression inside the parentheses will be evaluated first ( to true or false ). There is no limit on the number of parenthesis but they must come in pairs of open and closing parenthesis.In the above examples you must investigate 8 different case of each of the three variables being either above zero or less/equal to zero. For six of those eight possibilities above two expressions will give identical results, but not for the remaining two. There is no short cut to playing through all eight different options to discovering when the two expressions differ.
It's purpose is to negate an expression. The use of parentheses is encouraged.
Original expression :
a > 0 && b > 0
Negated expression :
! ( a > 0 && b > 0 )
Hence if "a" and "b" both have values greater than zero the original expression (now inside the parenthesis) will evaluate to "true" , the negated expression to "false". If either "a" or "b" or both are less or equal to zero then the negated expression evaluates to "true", right ?