bartop

palmoswerks ARCHIVE
Palm OS programming tips from a (former) CodeWarrior insider

header

Navigation

Search
Home
About
Stories
Stuff I Like
Articles
PilRC
CodeWarrior
palmos.techwood.org
DevTools List
Palm OS Dev FAQ

Variable Argument Lists and <stdarg.h>

One problem area for users of C and C++ on Palm OS is how to handle variable argument lists. This has always been a poorly understood area of the C language, and with Palm OS development not using ANSI C headers generally, it is prone to confusion.

A variable argument list is used when you have a function defined with an indefinite number of parameters, for example

int foo(int a, int b, ...)

When you call foo, you have to pass at least two parameters, but the call will allow any number. Usually, when you use these, you use one of the leading parameters to indicate how many variable parameters you have, or you setup a sentinal value that indicates end of the list.

A big problem with this form is type safety. Since the prototype doesn't specify the type of the variable paramters, the compiler does a few standard conversions. On Palm OS, this means that any 8-bit values are promoted to 16-bit. If you pass a Boolean or a UInt8 as a variable parameter, it will look like a Int16 on the other side.

To read these parameters, you use the va_start, va_end, va_arg, and va_copy macros defined in <stdarg.h> in C and <cstdarg> in C++. You declare a va_list variable as your argument pointer, then initialize it using va_start. This macro requires the last named parameter as an input to find the start of the variable parameters. You then use va_arg calls to advance the pointer, getting the values one by one. This macro won't signal the end of the list; you need to know that another way. When you're done, va_end is used to stop argument processing.

The Palm SDK implementation of va_start, as seen in unix_stdarg.h, has a bug if the last named parameter is a 8-bit value. It doesn't properly align the argument pointer. The version defined in CodeWarrior's MSL headers has this fix and should be used if possible.

brought to you by weblogger.com


Send feedback to combee@techwood.org
Copyright © 2004 Benjamin L. Combee
Palm OS is a registered trademark of PalmSource, Inc.
Metrowerks and CodeWarrior are registered trademarks of Metrowerks Inc.

The views expressed on this website/weblog are those of mine alone and do not necessarily reflect the views of PalmSource or Metrowerks.

This is a Manila Site

qwertYAK / frobnovich