int p = 100;
int q = 50;
int result;
result = (p > 90) + (q < 90);
What value will be assigned the variable result?
What meaning does the value have?
Cause: C doesn't have a boolean data type, which would prohibit
using an arithmetic operator on a logical expression. Instead, C
represents logical values as integers, and thus arithmetic is allowed
by the compiler, even though it makes no sense in the real world.
The programmer in the above example probably meant to use the logical
OR operator (||) but made a mistake. Unfortunately the C
compiler provides no assistance in identifying this error.
Languages with a built-in boolean type don't have this pitfall.
if (0 <= x <= 4)
{
printf("Yes!");
}
else
{
printf("No.");
}
Will always print "Yes!" for any value of x. The
correct syntax to use is:
if (0 <= x && x <= 4)
Will always print "Yes!" for any value of x because it
uses the assignment operator, not the equality operator. The
correct syntax to use is:
if ( x == 10 )
{
printf("Yes!");
}
if (x > 0)
sum = sum + x;
printf("Greater than zero");
printf("Mice love cheese");
if (x > 0)
{
sum = sum + x;
printf("Greater than zero");
}
printf("Mice love cheese");
if (x > 0);
{
printf("Greater than zero");
}