Sometimes newcomers to C/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 <stdio.h>
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;
}
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 <stdio.h>
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.
One other point: Writing the if statement as shown here
if(b != 0) printf("%d\n", a/b);
is redundant, potentially inefficient, and is considered bad style. Since the value of b
alone is sufficient to control the if, there is no need to test it against 0.
else executes. Otherwise, the condition is true (nonzero) and the division takes place.
One other point: Writing the if statement as shown here
if(b != 0) printf("%d\n", a/b);
is redundant, potentially inefficient, and is considered bad style. Since the value of b
alone is sufficient to control the if, there is no need to test it against 0.
No comments:
Post a Comment