CSADPRG_mod4_relational_boolean_expressions
original file
this is unedited
relational operators
- compared the values of the two operands
- relational expression: two operands and one relational operator
- the value of an expression is often Boolean except when Boolean is not a type in the lang
Examples of inequality operator: !=
(C-based), ~=
(Lua), .NE
or <>
(Fortran), <>
ML and F#, === and !==
(JavaScript, PHP to prevent coercion of the operands)
- Relational operators have lower precedence than arithmetic operators so for the expression
a + 1 > 2 * b
the arithmetic expressions will be evaluated first.
boolean expressions
- boolean variables, boolean constants, boolean operators, and relational expressions
- operators: AND OR NOT sometimes OR XOR
- usually take only boolean operands and produce boolean variables
- Arithmetic expressions can be the operands on relational expressions and relational expressions can be the operands of Boolean expressions, so they must be placed in different precedence levels.
For C-based languages (those prior to C99 had no boolean type and value so 0 was false and non-zero was true.)
Highest | postfix++, -- |
---|---|
unary +, -, prefix ++, --, ! | |
*, /, % |
|
binary +, - | |
<, >, <=, >= | |
=, != | |
&& | |
Lowest | || |
//try running
int main()
{
int a = 3;
int b = 2;
int c = 1;
int x = a > b > c;
printf("%d",x);
}
- The leftmost operator is evaluated first because in C relational operators are left associative, so a will be compared to b the result of which could either be 1 or 0. Afterwards, this result is compared with c. Note that the value of b is never compared to c.
//try running
public static void main(String[] args) {
int a = 1;
int b = 2;
int c = 3;
System.out.println(a > b > c);
}
// "would output bad operand types for binary operator"