TinyURL widget - shorten your URL's for free!

Enter a long URL to make tiny:

Saturday, July 9, 2016

Variable argument C functions with va_arg

Most tutorials online and those left standing for C give simplistic examples for the variable argument functions in <stdarg.h> for handling variable argument passing of various types.  The examples show you a simple data type like an integer and so on.

In this example, you can pass larger data types like structs into a variadic function just as easily. This means one can reproduce a simpler version of encapsulation/ polymorphism as in OOP languages. To present it first; here is a simple example that passes a struct, and then a struct inside a struct.



This passes a position struct containing x,y,z as coordinates, and the the same struct is passed to another function that accesses the inner position struct.   As a more complicated example, this suffices.

Now, when on considers pointer to functions and unions can be part of a struct, then you have all the encapsulation needed to contain an object struct that can be passed as argument. With unions, one can make a polymorphic version of a struct that can pass many types within the same container struct.

No comments:

Post a Comment