Saturday, June 20, 2009

Note to self, varargs stuff are all macros

So, I leared how to use varargs.

Not just declaring a varargs function and getting the arguments.
No, the trick was to get a va_list and pass it on to something like vswprintf. My problem was that whenever I had a number in my va_list, it would get scrambled in the output.

The thing to learn was that all the varargs stuff is just pointer arithmetic on a single char *, obfuscated by macros. The macros create hidden variables, which change state on every use of va_start(), va_arg(), va_list(). So, you can't use any of the arguments passed to your function if you want to pass that va_list on to another function. If you ever call va_arg(), you must reset everything bay calling va_end(), va_start() before you pass the va_list.

It's pretty rotten that
A) None of this stuff follows macro naming conventions, i.e VA_START
B) The side effects of using va_start and va_args are undocumented, not even on faqs or forums.

No comments:

Post a Comment