application_pgp-signature_part
< 1KViewDownload
"Short-circuit" is not a statement, but a description. If your book, in its
description of || and &&, does not mention that they're so-called
"short-circuit" operators, and does not explain what "short-circuit" means,
then you should look around for a better book.
When you have a statement:
if ( expression )
{
statement;
}
You know that if the "expression" evaluates to any non-0, or true, the
"statement" part is processed. If it evaluates to 0, or false, "statement"
is not processed.
This is very similar to:
( expression1 || expression2 )
If "expression1", which can be any expression, and evaluates to any non-0
value, then "expression2" does not get evaluated at all, because this is a
logical-or operation, and since you understand truth tables, you already
understand that the entire expression will be true. Therefore, "expression2"
is not evaluated, it is "short-circuited". If "(expression1 || expression2)"
is a part of a larger expression, its value will be true when "expression1"
evaluates to true, the rest of the expression then evaluated,
short-circuiting the "expression2" part, which does not get evaluated.
If you think about it, this is exactly the same as
if (expression1)
{
expression2;
}
There are only two minor differences between the || and the if() statement,
in C or C++. With the if() statement you can use any statement, or a
compound statement, for its conditional part (an expression is always a
valid statement). The right-hand side of the || operator is limited to an
expression (ignoring, for the moment, compiler-specific extensions, such as
a gcc-specific syntax for inserting statements in place of expressions).
Also, the body if the if() statement gets evaluated if the if() expression
is true, but the right-hand side of
Therefore, when you have:
(something || functioncall())
If "something" evaluates to true, the right-hand side of the || operator
does not get evaluated and the function call does not take place. This is
exactly identical to:
if (!(something))
{
functioncall();
}
The (void) part in the original code is just an explicit declaration that
the result of the || operator is to be discarded. It carries no meaningful
effect except as an explicit declaration that the expression's result is
discarded, which would occur anyway.
The same holds true for the && operator. Your homework assignment is to
understand why if
(expression1 || expression2)
is equivalent to
if (!(expression1))
{
expression2;
}
then why
(expression1 && expression2)
is equivalent to
if (expression1)
{
expression2;