Fog Creek Software
Discussion Board




Earlier printf question

There was an earlier post about passing various parameters to printf.

If I can remember correctly, the question was for a way to decide *at runtime* which parameters are passed, not at compile time.

This could easily be done in assembly -- after all, to the CPU, parameters to a function are just 32-bit values on the stack. Then I realized the same trick could be accomplished by casting all parameters to some common denominator, say void* or int, so you can safely switch between an int and a char* or whatever at runtime.

char* day = "Friday";
int x = 5;

void* v_day = (void*) day;
void* v_x = (void*) x;
printf ("%s is the %dth day of the week", v_day, v_x);

At this point, v_day and v_x can be safely interchanged (for whatever purposes that might be useful) since they are both void*.

Sorry if I missed the point of the original post.

Alex
Friday, December 19, 2003

Not sure if this is intended for a "generic" environment, but
this assumes that sizeof(void *) equals sizeof(int).  This
will work on Windows, but is not generally portable.

(I know because I had to fix code recently that did precisely
this, when I ported an app from a cpu with 32 bit ints to a cpu
with 16 bit ints and 32 bit pointers.)

A way to do variable arguments portably is with stdarg - this
will work no matter how big things are, and is quite portable.

foobarista
Saturday, December 20, 2003

I think the post was about the C language lacking a way to *pass* arbitrary arguments to functions. The varargs/stdargs mechanism is a standard for *receiving* arbitrary arguments. But if you have a pointer to a function that takes say N integers, and you don't know N until run-time, there is no clean way to call the function.

If you can modify the function, you could have it take a struct  array instead of individual arguments. Otherwise you have to resort to assembly-level stack hacking. (although there's a portable library for this now - libffi)

Dan Maas
Saturday, December 20, 2003

I cannot emphasize enough how much reflection is helpful. I don't miss C/C++ at all any more since I moved to C#. :-D

Brad Wilson (dotnetguy.techieswithcats.com)
Sunday, December 21, 2003

*  Recent Topics

*  Fog Creek Home