Two Useful C Idioms

Here are two of what are sometimes called idioms, small code templates which are used so frequently they become almost a part of the language. For example, the usual ascending for loop:
for (i = 0; i < n; ++i) {
    /* loop body */
}
This runs the loop body for every value from 0 up to but not including the limit value. Frequently, it doesn't harm anything for the loop to count down instead of up. In those cases, it can be written like this:
for (i = n; i--;) {
    /* loop body */
}
The loop variable is tested and decremented in one expression, lending brevity. The limit value is only computed once, so there is no confusion if it happens to be an expression. For efficiency freaks, this automatically moves potentially expensive limit value calculations out of the loop.

If the limit value calculation is really complicated, the loop can be written this way:

/*
long, complicated
limit value calculation
result in "i"
*/
while (i--) {
    /* loop body */
}
Having said all that, the above idiom is of dubious value, but I like it fairly well. The next idiom would have come in very handy when I was still barking my shins against the behaviour of = in C as opposed to BASIC or a number of other languages. Consider the usual if comparison statement:
if (foo == FOO_VALUE) {
    /* if body */
}
where FOO_VALUE is a compile-time constant. All too often, by oversight or typo, this can become:
if (foo = FOO_VALUE) {
    /* if body */
}
and havoc ensues. I've spent hours looking for bugs like this, and I could have avoided it all by coding the statement this way:
if (FOO_VALUE == foo) {
    /* if body */
}
This is just as valid as the original version, since == doesn't care about the order its arguments are in. But if I slip and turn the comparison into an assignment, the compiler will choke because I'm trying to assign to a compile-time constant. Same goes for when FOO_VALUE is an expression.

I hope you find these two little tricks useful. I learned them relatively recently, and liked them enough to adopt for my own programming. The second one in particular has probably saved me a lot of grief.

:;Smarasderagd:;