My notes on Variable arguments in C Functions

C allows you to define a function which can accept a variable number of arguments.

To use such functionality, you need to include stdarg.h header file. This file provides the functions and macros to implement the functionality of variable arguments.

Important Points:

  • Syntax of using variable length arguments:
        return_type function_name(parameter_list, int num, ...);
  • Last argument as elipses i.e. (three dots ...)
  • Argument before elipses in the function is always 'int' which represents the number of arguments passed
  • Create va_list type variable in the function definition. This is defined in stdarg.h file
  • Initialize va_list variable with the argument passed using va_start macro and the first parameter
  • Use va_arg macro to access each item inside the va_list
  • Clean the memory assigned to va_list using va_end macro

va_start function contains the magic code to initialize the va_list with the correct stack pointer. It must be passed the last named argument in the function declaration or it will not work.

This mechanism is used to write C Functions with optional number of arguments.

Look at man page of open system call.

 int open(const char *pathname, int flags);
 int open(const char *pathname, int flags, mode_t mode);

C codes demonstrating variable arguments




Comments

Popular posts from this blog

bb.utils.contains yocto

make config vs oldconfig vs defconfig vs menuconfig vs savedefconfig

PR, PN and PV Variable in Yocto