Saturday, July 14, 2007

Syntactic Notes

* Precedence
Postfix like ++, --, ->, (), [], ., etc have higher precedence than others and are left associative. Note the difference between postfix and prefix ++, --. Both prefix and postfix ones would increment/decrement its operand/variable directly. But prefix ones would return this variable while postfix ones returns the previous value of this variable. If the return value is not used further, like "i++;" and "++i;", prefix ones are preferred for efficiency since it do not need another temporary variable to store the previous value.

To apply the parenthesis to expressions is the best solution for the precedence confusion.

* Typedef/Define Complex Declarations
The key point is to understand the precedence of * and (), [], etc, when you identify the compound data types.
Two steps to declare compound data types by using typedef or #define: First figure out the correct type format; secondly remove the variable name (and the semicolon for #define) from the format and combine it with typedef/#define.
e.g. (*(void (*)())0)() and we could rewrite this as
typedef void (*fp)();
(*(fp)0)();
Try this now:
void (*((*p)[10]))(void);

* Semicolon
A single semicolon means a null statement in C. Two cases are special for semicolon usage.
One is if or while clause(semicolon might not necessary) and the other is the end of a declaration just before a function definition(semicolon is necessary since it might confuse the return type of the function).

* The Switch Statement
Keep in mind the weakness and strength of "break" in switch.

* The else Problem
The "else" is always associated with the closest unmatched if. The solution is to put curly brackets always even though only one statement is followed.

* Static
- static variables with the scopes only in one function
- static global variables with the scopes only in one file
- static global functions with the scopes only in one file

* +=; -=, *= and /=
The advantage of these operators are left values of them are just evaluated once when these l-values are compounds. For example,
array[i++] += y; =>
array[i] = array[i] + y; i++;
instead of
array[i++] = array[i++] + y;

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

No comments: