C Interview Questions and Answers


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 . Finally, if the 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 supply).

Posted by:Richards