<<< Date Index >>>     <<< Thread Index >>>

Re: [PATCH] Use NULL in vararg



On Wed, 10 Nov 2004 06:19:36 -0500 (EST), Thomas Dickey said:

> iirc, it is C++ that adds a cast, while C doesn't.

No. NULL needs to evaluate to a pointer value; thus the cast is
required unless pointer and integer have the same size.

In general you may always use 0 except for the vararg case.

  printf ("%s %d", 0, -1);

will only work on machines where sizeof (char*) == sizeof (int).  

In case an int is larger than a pointer and depending on the way
varargs are implemented, the printf in the above expression might
dereference the address 0x0000fffff for %s and use 0xffffxxxxx for %d
(with xxxx being trash from the stack).  Only using a string for the
second arg will make sure that the correct (in this case 16bit) value
will be used for %s.

If you look at the implementation of printf it gets obvious:

   while scanning FORMAT
     if "%s"
         char *value = va_arg (ap, char *);
     else if "%d"    
         int value = va_arg (ap, int);
         
va_arg() keeps an internal state in AP and moves the internal pointer
forward by the size of its second argument, so that the next va_arg()
can access the next argument.


Salam-Shalom,

   Werner