This preview has intentionally blurred sections. Sign up to view the full version.View Full Document
Unformatted text preview: Couple Notes about Boolean Expressions in C Not(!) operator Although the boolean operator "not" (!) is supposed to simply operate on boolean expressions, technically speaking, C does not have a type "boolean." In C, a boolean expression is actually an integer with a value of 1 or 0. Thus, even though it seems strange, the statement x = (x > y); would be perfectly valid in C (assuming that x and y were integer variables.) My advice would be to avoid using boolean expressions in places where one would typically expect arithmetic expressions. Similarly, avoid using arithmetic expressions in places where one would typically expect boolean expressions. An example of this is as follows: if (x) x++; else x--; The example in the text shows how expression !!5 evaluates to 1. This is quite confusing and code that involves such an expression should be avoided. Short-Circuit Evaluation When a C compiler encounters complex boolean expressions involving either && or ||, it attempts to do as little work as possible. For example, consider the following sequence of statements: int x, y; x = 3; y = 2; if ((x > 0) || (y < -1)) printf("The statement is true.\n"); The compiler evaluates the expression inside of the if statement from left to right and first determines that (x>0) is true. Then it sees that it is supposed to calculate the value of true "or" another expression. Regardless of whether that other expression is true or not, it's clear that the overall expression is true. Since this is the case, the compiler never even TRIES to evaluate the second expression, it simply skips doing so and moves onto the printf. Similarly, if a boolean expression is the and of two smaller expressions, if the first is false, the second is never even evaluated. Although this seems like a trivial detail, in some situations (in later examples), it will help us to shorten our code and avoid run-time errors. Compound and Empty Statements...
View Full Document
- Spring '08