Sometimes newcomers to C are confused by the fact that you can use any valid expression to control
the if or the ? operator. That is, you are not restricted to expressions involving the relational and
logical operators (as is the case in languages like BASIC or Pascal). The expression must simply
evaluate to either a true or false (zero or nonzero) value. For example, the following program reads
two integers from the keyboard and displays the quotient. It uses an if statement, controlled by the
second number, to avoid a divide-by-zero error.
/* Divide the first number by the second. */
#include
int main(void)
{
int a, b;
printf("Enter two numbers: ");
scanf(''%d%d", &a, &b);
if(b) printf("%d\n", a/b);
else printf("Cannot divide by zero.\n");
return 0;
}
This approach works because if b is 0, the condition controlling the if is false, and the else executes.
Otherwise, the condition is true (nonzero), and the division takes place.
Friday, September 19, 2008
The Conditional Expression
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment