Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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.

Also, please don’t downvote if it isn’t possible. I’m asking this because I’m very new to the syntax of macros and I’m not sure exactly how far they can go.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

The preprocessor itself is not capable of processing C types because macros are expanded before C code is even 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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading