[Coco] RE: Learning MW C (REALLY!)
James Jones
jamesjones01 at mchsi.com
Sat Aug 19 19:16:34 EDT 2006
Ries, Rich [S&FS] wrote:
> My other problem was remembering if | was logical or bitwise OR. The
> same for && and ^. I finally wrote a header file that I can #include in
> my files. (Drives everyone else crazy, but...) Here it is:
>
> [code]
> /* Logical operators */
> #define L_AND &&
> #define L_OR ||
> #define L_NOT !
>
> /* Bitwise operators */
> #define b_and &
> #define b_or |
> #define b_xor ^
> #define b_not ~
To people thinking of learning C: I urge you not to use such macros.
Eventually, you'll find yourself working on someone else's code who
doesn't use them, so you'll have to learn the operators eventually, and
conversely, someone else will have to work on your code, and the macros
that allegedly make the code clearer for you will be immediately ripped
out, and the other person will be much harder to work with afterwards.
The "Boolean" operators are &&, ||, and !. && and || are also
short-circuit; it's guaranteed that
x && y behaves exactly like (x != 0) ? (y != 0) : 0
x || y behaves exactly like (x != 0) ? 1 : (y != 0)
i.e. if the value can be determined just from x, y isn't evaluated.
^ is exclusive or, and because you always have to evaluate both
operands, there's no "short-circuit" version--there can't be. &, |, and
~ are bitwise and, or, and not respectively.
> /*
> * Bit operations -
> * Note there is no limit to how many bits are in a byte.
> *
> * tobit(20000) will work....
> *
> */
> #define tobit(x) (1 << ((x)))
That's not correct. 1 has type int, so that
long
setbit(ell, bitno)
long ell;
int bitno;
{
return ell | tobit(bitno);
}
will not work if bitno > 8 * sizeof(int). Strictly speaking, for such
values, the result is undefined; a standard-conforming compiler could
insert code to phone out for anchovy pizza or start the self-destruct
sequence.
James
More information about the Coco
mailing list