How to verify a type in a C macro

ぐ巨炮叔叔 提交于 2019-12-02 21:04:01

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.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!