Question 15.8

How can I discover how many arguments a function was actually called with?


This information is not available to a portable program. Some old systems provided a nonstandard nargs function, but its use was always questionable, since it typically returned the number of words passed, not the number of arguments. (Structures, long ints, and floating point values are usually passed as several words.)

Any function which takes a variable number of arguments must be able to determine from the arguments themselves how many of them there are. printf-like functions do this by looking for formatting specifiers (%d and the like) in the format string (which is why these functions fail badly if the format string does not match the argument list). Another common technique, applicable when the arguments are all of the same type, is to use a sentinel value (often 0, -1, or an appropriately-cast null pointer) at the end of the list (see the execl and vstrcat examples in questions 5.2 and 15.4). Finally, if their types are predictable, you can pass an explicit count of the number of variable arguments (although it's usually a nuisance for the caller to generate).

References: PCS Sec. 11 pp. 167-8


Read sequentially: prev next up top


This page by Steve Summit // Copyright 1995 // mail feedback