Saturday, July 14, 2007

Lexical Notes

* Assignment and Logic Comparison (i.e. = is not ==)
In most cases, the solution is to switch the arguments in comparison, like if (0 == x) instead of if (x == 0). This is invalid if both arguments are variables.

* Bit Operations and Logic Operations (i.e. & is not &&, | is not ||)
& and | treat their arguments as a sequence of bits while && and || does as 'true' or 'false'.
For bit operations, the portable formats:
#define BIT3 (0x1 << 3)
unsigned int a = 0x1;
a |= BIT3; /* Set */
a &= ~BIT3; /* Clear */

* Multi-character Tokens
How to explain these cases?
y = x/*p; z = y+++x; (assuming p is the pointer)
The greedy interpretion rule!

Reference:
Andrew Koenig, "C Traps and Pitfalls", AT&T Bell Lab

No comments: