Coze
Coze

Reputation: 83

Give type as argument like va_arg in C

va_arg(a,type) macro expands to __builtin_va_arg(a,type) which is built-in part of compiler.

Is it possible to implement type based functionality, if yes how?

Upvotes: 4

Views: 1840

Answers (2)

masoud
masoud

Reputation: 56549

Notice that va_arg cannot determine the actual type of the argument passed to the function, but uses whatever type is passed as the type macro argument as its type.

Lets see how va_arg works, one possibility from here, is

#define va_arg(ap,t) (*(t *)((ap += _INTSIZEOF(t)) - _INTSIZEOF(t)))

First of all, it's a MACRO not a function.

If you want write a type base MACRO as same as var_arg, you have two main tools, pointers and sizeof.

You can increase/decrease/lookup a pointer with sizeof steps.

Upvotes: 3

md5
md5

Reputation: 23737

With the preprocessor, you can indeed implement type based functionality, although it is limited. Don't forget that #define directives act with copy/paste, so you can not compare types in C standard, for instance(*).

However, you can reuse a type argument to build type-generic functions. Here is an example of a min generic function:

#define DEFINE_MIN(type)        \
int min_##type(type a, type b)  \
{ return a < b ? a : b; }       

By the way, a gcc extension, typeof, gives the type of an expression (it doesn't rely on the programmer arguments anymore). Moreover, more recently, the C11 _Generic keyword permits you to write different treatment for expressions of different types.

(*) In the case of va_arg, the type argument is often use to get the size of type and type*.

Upvotes: 3

Related Questions