Expert C Programming

(Jeff_L) #1

rationale is that it makes automated generation of C easier. The claim would be more credible if
trailing commas were permitted in every comma-sepa-rated list, such as in enum declarations, or
multiple variable declarators in a single declaration. They are not.


Handy Heuristic


First Time Through


This hint shows a simple way to get a different action the first time through a section of
code.


The function below will do a different action on its first invocation than on all subsequent
calls. There are other ways of achieving this; this way minimizes the switches and
conditional testing.


generate_initializer(char * string)


{


static char separator='';


printf( "%c %s \n", separator, string);


separator = ',';


}


The first time through, this will print a space followed by an initializer. All subsequent
initializers (if any) will be preceded by a comma. Viewing the specification as "first time
through, prefix with a space" rather than "last time through, omit the comma suffix" makes
this simple to program.


The claim is hard to believe, as an automated program can output a comma or no comma by having a
statically declared character initialized to space and then set to comma. This will exhibit the correct
behavior and is trivial to code. There are other examples of comma-separated items in C, where a
comma may not terminate the list. The unnecessary, but allowed, comma after the last initializer
serves mostly to muddy the waters of an already murky syntax.


Too Much Default Visibility


Whenever you define a C function, its name is globally visible by default. You can prefix the function


name with the redundant extern keyword or leave it off, and the effect is the same. The function is


visible to anything that links with that object file. If you want to restrict access to the function, you are


obliged to specify the static keyword.

Free download pdf