Logical AND OR and NOT

Logical AND

In simple terms, && is true (1) if both sides of the expression returns NOT false (0).

For Example:

	/* These all return TRUE (1) */

	if (4 && 5) return();

	return( i && j);

The expression is evaluated 'Left to Right' If any part of the expression returns ZERO - The evaluation ends. This is called "short circuiting" and can cause serious problems if you don't understand it.

For example:

	if ( i-i && j++) k=1

The left side (i-i) resolves to 0, so j is not incremented and the resulting condition is false so k is not changed.

Logical OR

OR also evaluates 'Left to Right' and will stop when an expression returns true. SO WATCH OUT....

	if ( i+i && j++) k=1

What are j and k going to be when this code is executed????? i + i evaluates to 6, which is true (not zero) and so the rest of the condition is not evaluated, e.g. j is still 2. The condition is true, so k will be set to 1.

This can also be somewhat useful to do things like checking a pointer is not null before calling a routine that depends on a valid pointer, or doing a low cost condition first before doing a second condition which is more expensive to compute. e.g. if (0==a && f/123>2.3334) will execute faster than if (f/123>2.3334 && 0==a). However, because each condition is type changed into a boolean (1 or 0 only) before being returned, you can NOT do things like i = a || 1 to default i to 1 if a is zero, which works nicely in JavaScript, Perl, LUA, etc... In C or C++ i will be 1 no matter what a is, because a will be converted to true (1) if it isn't zero, and if it is zero, the 1 will be converted to true (1) and returned instead.

Logical NOT

NOT reverses the logical state of its operand. If the operand is 0, 1 is returned, else 0 is returned.

	!4	/* Returns 0	*/
	!-4	/* Returns 0	*/
	!1	/* Returns 0	*/
	!0	/* Returns 1	*/

Top Master Index Keywords Functions

Martin Leslie

See also: