In a message dated 11/10/99 7:43:41 PM, [EMAIL PROTECTED] writes:
>You don't need the macros if all the variable parameters are the same type,
>for example CharPtr. This is a very standard C language technique.
>
>int foo (int count, CharPtr p1, ...) {
> CharPtr *pPtr = &p1;
> int i;
> for ( i = 0 ; i < count && *pPtr != NULL ; i++) {
> CharPtr ptr = pPtr[i];
> ...................... // process each parameter in
turn....
> }
> return i;
>}
>
>However, the macros look more elegant, which is one reason they exist.
The other reason the macros exist is because this isn't legal C. Yes, it's
common--but technically, the way the C compiler performs in this situation is
left to the discretion of the implementor. Anything, including crashing, is
allowed.
First off, there is no garantee about the way the parameters are stored. Your
code explicitly assumes that parameters follow each other in memory in
sequential order. This is common, but not required. From the ANSI C standard:
"6.7.1. ... Each parameter has automatic storage duration. Its identifier is
an lvalue. The layout of the storage for parameters is undefined."
As a point of fact, some compilers will pass parameters in registers, and
your code will fail. Others will pass the parameters in reverse order. It's
unusual, but allowed.
Another subtle point is that a function that accepts variable numbers of
arguments is _required_ to process them with the macros. Again from the ANSI
C standard:
"7.8.1. ... The va_start and va_end macros shall be invoked in the function
accepting a varying number of arguments, if access to the varying arguments
is desired."
You have to be real careful when the standard says "shall." Here's why:
"3.16. ... If a 'shall' or 'shall not' requirement that appears outside of a
constraint is violated, the behavior is undefined. ..."
And earlier in the same section:
"3.16. undefined behavior: Behavior ... for which this International Standard
imposes no requirements. Permissable undefined bahavior ranges from ignoring
the situation completely with unpredictable results ..."
That last phrase, "unpredicatable results," is the standard's oh-so-polite
way of saying, "crash."
For variable number of arguments, use the macros. Used properly, they
garantee correct performance under any ANSI C compiler. If not used, they
garantee the program will crash under some perfectly legal implementations of
ANSI C.
Mike Westerfield