Search code examples
cpreprocessor

Typechecking in C preprocessor


I was hoping to implement optional arguments in c by using macros to set a function based on the variable type.

#define dostuff(BOOL) dostuffwithbool(BOOL)
#define dostuff(INT) dostuffwithint(INT)

Is this kind of thing possible at all? (even though I know it probably isn't). I'd accept any answer no matter how long or hacky.


Solution

  • The preprocessor itself is not capable of processing C types because macros are expanded after tokenization of program but the before syntactical constructs of C language are parsed.

    Depending on your application you can use _Generic available from C11. It is basically switch-case over types.

    #define dostuff(val)                    \
      _Generic((val), bool: dostuffwithbool \
                    , int:  dostuffwithint) (val)
    

    Note that this solution will not work if dostuffwithbool/dostuffwithint were function-like macros. The macros would not be expanded due to a lack of ( following a macro.