C Language

Brace Yourself

The problem occurs because of a missing semicolon. Many "old hand" C programmers would say the solution is simply to add the semicolon (after a few hours of debugging!). But does the following correction give us a safe program?

 If (xcnt < 2)
   return;
 date = x[0];
 time = x[1];

What if we decide to add an error message?

 if (xcnt < 2)
   printf("Timestamp array is too small\n");
   return;
 date = x[0];
 time = x[1];

Indeed, this is the ultimate "safe" program - for valid arrays, it never does anything but return, terminating program execution! The code's execution is identical to

 if (xcnt < 2) {
   printf("Timestamp array is too small\n");
 }
 return;
 date = x[0];
 time = x[1];

For quick coding, C lets you omit the { } around a conditional statement, a shortcut most published C programs take advantage of. You will be tempted to take this shortcut, too. Don't! Ever! Always enclose conditional code in braces. The errors introduced by incorrectly matched conditions and subordinate statements are very hard to ferret out. Our original example is better coded like this:

 if (xcnt < 2) {
   return;
 }
 date = x[0];
 time = x[1];

Note that using braces also lets the compiler catch a missing semicolon, so you get lots of protection by following this simple rule.

Unwinding this example also suggests a rule I mentioned in Chapter 2: Do all your assignments as separate statements, not as part of a more complex expression. Another helpful rule is: Use parentheses around expressions in return statements. For example, if you really did want to return the date after assigning it to a global variable, you might code

 if (xcnt < 2) {
   date = x[0];
   return  (date);
 }

This doesn't solve the original problem we looked at, but it does show how to code return statements so you're less likely to be tripped up by other problems with complex expressions.