The function construct, itself, forms another way to affect flow of control through a whole program. This will be discussed later in the course.
#define TRUE 1 #define FALSE 0
x == y // x is equal to y x != y // x is not equal to y x < y // x is less than y x <= y // x is less than or equal to y x > y // x is greater than y x >= y // x is greater than or equal to y
We also have Boolean operators for combining expressions. Again, these operators return 1 for true or 0 for false
x && y // the AND operator -- true if both x and y are true x || y // the OR operator -- true if either x or y (or both) are true !x // the NOT operator (negation) -- true if x is false
These operators will be commonly used as test expressions in selection
statements or repetition statements (loops).
(x > 0 && y > 0 && z > 0) // all three of (x, y, z) are positive (x < 0 || y < 0 || z < 0) // at least one of the three variables is negative ( numStudents >= 20 && !(classAvg < 70)) // there are at least 20 students and the class average is at least 70 ( numStudents >= 20 && classAvg >= 70) // means the same thing as the previous expression
(d != 0 && n / d > 0) // notice that the short circuit is crucial in this one. If d is 0, // then evaluating (n / d) would result in division by 0 (illegal). But // the "short-circuit" prevents it in this case. If d is 0, the first // operand (d != 0) is false. So the whole && is false.
if (expression)
statement
else
statement
if (expression)
statement
;
expression;
if (grade >= 68)
printf("Passing");
// Notice that there is no else clause. If the grade is below 68, we move on.
if (x == 0)
printf("Nothing here");
else
printf("There is a value");
// This example contains an else clause. The bodies are single statements.
if (y != 4)
{
printf("Wrong number");
y = y * 2;
counter++;
}
else
{
printf("That's it!");
success = 1;
}
Multiple statements are to be executed as a result of the condition being true or false. In this case, notice the compound statement to delineate the bodies of the if and else clauses.
// What output will it produce if val = 2? Does the "too bad" statement really go with the "else" here?
if (val < 5)
printf("True\n");
else
printf("False\n");
printf("Too bad!\n");
* Indentation is only for people! It improves readability, but means nothing to the compiler.
if (x == 1 || 2 || 3)
printf("x is a number in the range 1-3");
if (x > 5) && (y < 10)
printf("Yahoo!");
if (response != 'Y' || response != 'N')
printf("You must type Y or N (for yes or no)");
switch (expression)
{
case constant:
statements
case constant:
statements
... (as many case labels as needed)
default: // optional label
statements
}