How to verify a type in a C macro

后端 未结 1 413
Happy的楠姐
Happy的楠姐 2021-02-03 10:57

I have been thinking about ways to validate types in C macros and so far the best way that I have come up with is this:

#define ASSERT_PTYPE(TYPE, VALUE) (0 &         


        
1条回答
  •  庸人自扰
    2021-02-03 11:41

    With C99 and compound literals you can do something like

    #define ASSERT_TYPE(TYPE, VALUE) ((TYPE){ 0 } = (VALUE))
    

    This ensures that VALUE is assignment compatible to TYPE. The expression returns an rvalue because of the assignment.

    Compound literals work in function scope as well as in file scope and any decent compiler should optimize the extra object that is created out of the way.

    Addition: TYPE in that macro can be any valid type name, e.g pointer double*, struct or union struct toto, besides arrays. Array type such as double[4] wouldn't work because of the assignment. Use pointer to array double(*)[4] instead, e.g as in

    double A[4];
    (*ASSERT_TYPE(double(*)[4], &A))
    

    where the second line again is a lvalue of type double[4] that is compile time checked for that property.

    0 讨论(0)
提交回复
热议问题