Boltar said:
Why does C do lazy evaluation for logical boolean operations but not
bitwise ones?
Ie: the following program prints "1 2" , not "1 1" under gcc
main()
{
int a = 1;
int b = 1;
0 && ++a;
0 & ++b;
printf("%d %d\n",a,b);
}
Surely the bitwise boolean ops are just as appropriate for doing lazy
evaluation with?
No, they are not.
An important goal of C was to generate efficient code. The operands of the
logical operators &&, ||, !, and ? must usually be tested at run time for a
true or false value, normally by a conditional branch. There is no extra
cost to short circuit evaluation and it is a short-hand convenience to
programming.
The boolean operators normally map to bit-wise and, or, xor, and
complement, which return a result value. In general, zero is not a special
case for the operators and no zero test is needed. Performing short
circuit evaluation at run time would be added code and execution time with
little payoff.
It would also lead to less useful results using operators with side
effects. Defining
a = b .& c++; /* where .& is defined as bitwise and with no
evaluation of second operand when first operand is 0 */
is less useful than the current
a = b & c++;
for me.
Compilers can and do take advantage of special values when known at compile
time. a += 0; will generate no code on many compilers if a is not
volatile. But if you write
a += 0 * y++;
the compiler must increment y, even though it is not needed for the
determination of a. 0 & ++b in your example code falls into the same category.