Wandering Thoughts archives


The limitations of C's varargs support

I've noted before that dealing with varargs functions in C is vaguely annoying (although not as annoying as in the days before the ANSI C stdarg support). One of those annoyances is that C's stdarg support is limited compared to what you can do in languages with first class support for variable argument counts.

The core limitation in C is that you can't manipulate the list of variable arguments that your function gets. Instead you have two choices; you can pass it completely unaltered to a function that takes a va_list argument, or you can entirely consume it yourself. You can't add things to the list, remove things from the list, or create your own va_list from scratch containing a mixture of things, and in turn this means that you can't create certain sorts of varargs APIs in C.

(Whether these APIs are a good idea is another question.)

Update: I'm somewhat wrong about this, see CStdargWhyWrong. You can effectively pop stuff off the front of a va_list before you pass it to another function.

To answer the obvious question: by first class support for variable arguments, I mean that you can both manipulate (and create) varargs argument lists and call an arbitrary function with a varargs argument list, whether you got it because you're a varargs function yourself or because you made it up from scratch. C doesn't support either of these because it's constrained by a desire for efficient implementation of varargs support, one that doesn't require dynamic memory allocation or the like.

(In theory a C compiler could support the latter under some circumstances; basically, it would need to know the called function's exact argument list and behavior if the va_list was not an exact match for this would be undefined.)

programming/CStdargLimitations written at 01:06:17; Add Comment

Page tools: See As Normal.
Login: Password:
Atom Syndication: Recent Pages, Recent Comments.

This dinky wiki is brought to you by the Insane Hackers Guild, Python sub-branch.