4. • Produce 0 (false) or 1 (true) when used in expressions
• Can be used to compare integers and floating-point numbers
Operands of mixed types allowed
• The precedence of the relational operators is lower than that of the
arithmetic operators
• Left-associative
5.1 Logical Expressions: Relational Operators
Symbol Meaning
< Less than
> Greater than
<= Less than or equal to
>= Greater then or equal to
5. 5.1 Logical Expressions: Equality Operators
• “=“ character in C
1. The assignment operator: single = character (“=“)
2. The equality operator: two adjacent = characters (“==”)
• Produce 0 (false) or 1 (true) when used in expressions
• Left-associative
• The equality operators have lower precedence than the relational
operators
• The relational and equality operators return integer values
Tricky coding using this isn’t a good idea -> hard to read!
Symbol Meaning
== Equal to
!= Not equal to
i < j == j < k (i < j) == (j < k)
(i >= j) + (i == j) The value is 0, 1, or 2
6. 5.1 Logical Expressions: Logical Operators
• Produce 0 (false) or 1 (true) when used in expressions
1. Treat any nonzero operand as true value
2. Treat any zero operand as false value
• “&&” and “||” short-circuit evaluation of their operands
These operators first evaluate the left operand.
Then the right operand is evaluated if the value of the expression cannot be deduced from the
value of the left operand alone.
Side effects may not always occur
The ! Operator has the same precedence as the unary plus and minus operators,
and is right associative
The precedence of && and || is lower than that of the relational and equality
operators, and is left associative
Symbol Meaning
! Logical negation
&& Logical and
|| Logical or
(i != 0) && (j / i > 0)
(i > 0) && ++j > 0
7. 5.2 The if Statement
• The parentheses around the expression are mandatory
Part of if statement
• If the value of the expression is nonzero, which C interprets as true
The statement after the parentheses is executed
• Don’t confuse == (equality) with = (assignment)
If (i == 0)
If (i = 0) -> always false
• Often the expression in an if statement will test
1. Whether a variable falls within a range of values: 0 ≤ i < n
2. The opposite condition (outside the range) : i < 0 or i ≥ n
if ( expression ) statement
If (0 ≤ i && i < n)
If (i < 0 || i ≥ n)
8. Equality and Assignment Operators in if
• Using if (0 == i) to let compiler produce error message if use “=“ instead of
“==“
• Many compilers are capable of checking for suspect uses of the = operator
in if conditions
GCC compiler will perform check if the –Wparentheses option is used or if –Wall is
selected
GCC allows the programmer to suppress the warning in a particular case by
enclosing the if condition in a second set of parentheses
if ( (i == j) ) …
9. 5.2 The if Statement: Compound Statements
• Putting braces around a group of statements can force the compiler
to treat it as a single statement
Each inner statement still ends will a semicolon
But the compound statement itself does not
• Compound statements are also common in loops and other places
where the syntax of C requires a single statement, but we want more
than one
if ( expression ) { statements }
if (line_num == MAX_LINES) {
line_num = 0;
page_num++;
}
{
line_num = 0;
page_num++;
}
10. Coding Style for Compound Statements
1. The K&R style
2. The Allman style
3. The Whitesmiths style
4. The GNU style
• According to The New Hacker’s Dictionary, there are 4 common styles of
indentation and brace placement
if (line_num == MAX_LINES) {
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
if (line_num == MAX_LINES)
{
line_num = 0;
page_num++;
}
11. 5.2 The if Statement: The else Clause
• If the expression in parentheses has the value 0, the statement that follows
the word else is executed
• Both inner statements end with a semicolon
• Coding Style
Align else with if
If only one short statement, statement can be put on the same line as the if and else
if statements can be nested to any depth
Adding braces to statements even when they’re not necessary
1. The program becomes easier to modify, because more statements can easily be added to any if
or else clause
2. It helps avoid errors that can result from forgetting to use braces when adding statements to
an if or else clause
if ( expression ) statement else statement
12. 5.2 The if Statement: Cascaded if Statements
• Use cascaded if statements
to test a series of conditions
• C programmers align each
else with the original if
1. Avoid the problem of
excessive indentation when
the number of tests is large
2. Assure the reader that the
statement is nothing more
than a series of tests
if (n < 0)
printf (“n is less than 0n”)
else
if (n == 0)
printf (“n is equal to 0n”)
else
printf (“n is greater than 0n”)
if (n < 0)
printf (“n is less than 0n”)
else if (n == 0)
printf (“n is equal to 0n”)
else
printf (“n is greater than 0n”)
if ( expression )
statement
else if ( expression )
statement
…
else if ( expression )
statement
else
statement
13. 5.2 Calculating a Broker’s Commission
• The minimum charge is $39
Transaction size Commission rate
Under $2,500 $30 + 1.7%
$2,500~$6,250 $56 + 0.66%
$6,250~$20,000 $76 + 0.34%
$20,000~$50,000 $100 +0.22%
$50,000~$500,000 $155 + 0.11%
Over$500,000 $255 + 0.09%
14. 5.2 The if Statement: The “Dangling else”
Problem
1. C follows the rule that an else clause belongs to the nearest if
statement that hasn’t already been paired with an else
2. Using braces can clearly define the pair of if and else
if (y != 0)
if (x != 0)
result = x/y;
else
printf (“Error: y is equal to 0n”)
if (y != 0)
if (x != 0)
result = x/y;
else
printf (“Error: y is equal to 0n”)
if (y != 0) {
if (x != 0)
result = x/y;
}
else
printf (“Error: y is equal to 0n”)
1.
2.
15. 5.2 The if Statement: Conditional Expressions (1/2)
• Conditional operators (? and : )
1. Must be used together
2. Allow an expression to produce one or two values depending on the value
of a condition
3. Require three operands: ternary operator
• expression 1, 2, 3 can be expressions of any type
• “if expression1 then expression2 else expression3”
1. expression1 is evaluated first
2. If value of expression1 isn’t zero, then expression2 is evaluated
3. If value of expression1 is zero, then expression3 is the value of the
conditional
expression1 ? expression2 : expression3
int i, j, k;
i = 1;
j = 2;
k = i > j ? i : j; /* k is now 2 */
k = (i >= 0 ? i : 0)+ j; /* k is now 3 */
16. • Conditional expressions tend to make programs shorter but harder to
understand
• A few places in which conditional expressions are tempting
1. return statement
2. printf
3. Certain kinds of macro definitions
if (i > j)
return i;
else
return j;
return i > j ? i : j;
if (i > j)
printf(“%dn”, i);
else
printf(“%dn”, j);
printf(“%dn”, i > j ? i : j);
Macro
definitions
Ch 14.3
5.2 The if Statement: Conditional Expressions (2/2)
17. Mixed-Types in Conditional Expressions
i > 0 ? i : f;
i is integer
f is floating-point number
The expression has type float
18. 5.2 The if Statement: Boolean Value in C89
• The C language lacked a proper Boolean type for many years
There is no defined in the C89 standard
• Work around
1. Declare an int variable and then assign it either 0 or 1
Not contribute much to program readability
It is not obvious that flag is to be assigned only Boolean values
2. Define macros with names such as TRUE and FALSE
3. Carry 2. idea one step further, we can define a macro that can be used as a type
BOOL can take the place of int when declaring Boolean variables
4. Better way in later chapter by using type definition and enumerations
#define TRUE 1
#define FALSE 0
Test whether flag is True False
1st way if (flag == TRUE) … if (flag == FALSE) …
2nd way if (flag) … if (!flag) …
Better way
1. More concise
2. Still work correctly if flag has
a value other than 0 or 1
int flag
flag = 0;
…
flag = 1;
#define BOOL int;
BOOL flag;type definitions
Ch 7.5
enumerations
Ch 16.5
19. 5.2 The if Statement: Boolean Values in C99
• C99 provides the _Bool type
An unsigned integer type
Can only be assigned 0 or 1
− Attempt to store a nonzero value into a _Bool variable will cause the variable to be
assigned 1
Is legal to
− Perform arithmetic on _Bool variables
− Print a _Bool variables
− Test _Bool variables in an if statement
•C99 also provides a new header <stdbool.h>
Provide a macro, bool, that stands for _Bool
Supply macros named true and false
#include <stdbool.h>
…
bool flag;
_Bool flag;
Unsigned
integer types
Ch 7.1
<stdbool.h>
header
Ch 21.5
20. _Bool in C99
• Why use _Bool instead of bool or Boolean?
Existing C programs might already define these names, causing older code not to
compile
The C89 standard specifics that names beginning with an underscore followed by
an uppercase letter are reserved for future use and should not be used by
programmers
21. 5.3 The switch Statement (1/3)
• As an alternative to cascaded if statement, C provides the switch
statement
Easier to read than cascaded if statement
Often faster than if statements
if (grade == 4)
printf (“Excellent”);
else if (grade == 3)
printf (“Good”);
else if (grade == 2)
printf (“Average”);
else if (grade == 1)
printf (“Poor”);
else if (grade == 0)
printf (“Failed”);
else
printf (“Illegal grade”);
switch (grade) {
case 4:
printf (“Excellent”);
break;
case 3:
printf (“Good”);
break;
case 2:
printf (“Average”);
break;
case 1:
printf (“Poor”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
break
statement
Ch 6.4
Transfer control to the
statement following the
switch
If the value of grade doesn’t match
any of the choices listed, the
default case apply
default
1. Doesn’t need to come last
2. Not required
Control simply passes to the next
statement after the switch if
default is missing and the value of
the controlling expression doesn’t
match any of the case labels
22. 5.3 The switch Statement (2/3)
switch ( expression ) {
case constant-expression : statements
…
case constant-expression : statements
default : statements
}
Controlling expression
1. Integer expression
2. Characters are treated as integers in C
3. Floating-point numbers and strings don’t qualify
Case labels
1. Each case begins with a label
2. constant-expression
1. Ordinary expression
2. Except it can’t contain
variables or function calls
3. An integer (characters
are also OK)
Statements
1. No braces are required
around the statements
2. The last statement in each
group is normally break
characters
Ch 7.3
23. 5.3 The switch Statement (3/3)
• Duplicated case labels aren’t allowed
• The order of the cases doesn’t matter
• Only one constant expression may
follow the word case
Several case labels may precede the
same group of statements
• There is no way to write a case label
that specifies a range of values
switch (grade) {
case 4:
case 3:
case 2:
case 1:
printf (“Passing”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
switch (grade) {
case 4: case 3: case 2: case 1:
printf (“Passing”);
break;
case 0:
printf (“Failed”);
break;
default:
printf (“Illegal grade”);
break;
}
24. 5.3 The switch Statement: The Role of the break
Statement
• switch statement is a form of “computed jump”
When the controlling expression is evaluated, control jumps to
the case label matching the value of the switch expression
A case label is just a position marker within the switch
When the last statement in the case has been executed, control
“falls through” to the first statement in the following case
− The case label for the next case is ignored
• Falling through from one case into the next is rare
It is good to point out any deliberate omission of break
• The last case in a switch statement is common to put one
break there
If cases should later be added
switch (grade) {
case 4: case 3: case 2: case 1:
num_passing++;
/*FALL THROUGH*/
case 0: total_grade++;
break;
}
switch (grade) {
case 4: printf (“Excellent”);
case 3: printf (“Good”);
case 2: printf (“Average”);
case 1: printf (“Poor”);
case 0: printf (“Failed”);
default: printf (“Illegal grade”);
}
26. Other Form for switch Statement?
• The switch statement is b bit more general than described in this chapter
A switch statement can contain labels that aren’t preceded by the word case
switch (…) {
…
defualt: …
}
switch ( expression ) {
case constant-expression : statements
…
case constant-expression : statements
default : statements
}
switch ( expression ) statements
Also legal, because “default”
is an ordinary label
27. Coding Style of switch
1. Put the statements in each case
after the case label
Fine when the statements in each case
are short and there are relatively few of
them
2. Put the statements under the case
label, indenting the statements to
make the case label stand out
Better for large switch statements in
which the statements in each case are
complex and/or numerous
switch (grade) {
case 4: printf (“Excellent”);
break;
case 3: printf (“Good”);
break;
default: printf (“Failed”);
break;
}
switch (grade) {
case 4:
printf (“Excellent”);
break;
case 3:
printf (“Good”);
break;
default:
printf (“Failed”);
break;
}
• There are at least two common methods
switch (grade) {
case 4: printf (“Excellent”); break;
case 3: printf (“Good”); break;
default: printf (“Failed”); break;
}