Computers are more than relentless number crunchers. They have the capability to compare values, and this capability is the foundation of computer decision making. C++ relational operators embody this ability.
Because characters are represented by their ASCII codes, you can use these operators with characters too! They don't work with C-style strings. But they work with the string class! Each relational expression reduces to the bool value true if the comparison is true, and to the bool value false if the comparison is false. So these operators are well suited for use in a loop test expression.
This are the relational operators:
< Is less then.
<= Is less then or equal to
== Is equal to
> Is greater then
>= Is greater then or equal to
!= Is not equal to
The six relational operators exhaust the comparisons C++ enables you to make for numbers. If you want to compare two values to see which is the more beautiful or the luckier, you must look elsewhere.
Here are some sample tests:
for (x = 20; x > 5; x--) // continue while x is greater than 5
for (x = 1; y != x; ++x) // continue while y is not equal to x
for (cin >> x; x == 0; cin >> x) // continue while x is 0
The relational operators have a LOWER PRECEDENCE than the arithmetic operators. That means:
x + 3 > y - 2 // Expression 1
corresponds to this:
(x + 3) > (y - 2) // Expression 2
and NOT to the following
x + (3 > y) - 2 // Expression 3
Because the expression (3 > y) is either 1 or 0 after the bool value is promoted to int, Expressions 2 and 3 are both valid. But most of us would want Expression 1 to mean Expression 2, and that is what C++ does.
Abonneren op:
Reacties posten (Atom)
Geen opmerkingen:
Een reactie posten