如何验证 C 宏中的类型
我一直在考虑验证 C 宏中类型的方法,到目前为止,我想到的最好方法是:
#define ASSERT_PTYPE(TYPE, VALUE) (0 && (*(int (*)(TYPE*))0)(VALUE))
这显然需要类型名称和指向该类型的指针。也可以制作类似的 ASSERT_TYPE 宏。这似乎与 GCC 配合得很好。如果类型不匹配,它甚至会给出非常有用的错误消息。问题是我不能完全确定这是有效的 C 语言还是最好的方法。
据我了解,标准说您可以强制转换函数指针,但调用强制转换函数指针的结果是未定义的。在这种情况下,不可能在运行时调用该函数。这是否足够好,或者标准是否意味着您甚至无法编写无法调用的调用强制转换函数的代码?
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 && (*(int (*)(TYPE*))0)(VALUE))
This obviously expects a type name and a pointer to that type. A similar ASSERT_TYPE macro can be made as well. This seems to work quite well with GCC. It even gives a very helpful error message in the case that the types do not match. The problems are that I am not completely certain that this is valid C or the best way for that matter.
As I understand it the standard says that you can cast a function pointer, but the result of calling the cast function pointer is undefined. In this case it is impossible for the function to be called at runtime. Is that good enough or does the standard mean that you cannot even write code that cannot be called that calls the cast function?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
使用 C99 和复合文字,您可以执行类似的操作,
这可确保
VALUE
与TYPE
的赋值兼容。由于赋值,表达式返回一个右值。复合文字在函数作用域和文件作用域中工作,任何像样的编译器都应该优化创建的额外对象。
补充:该宏中的
TYPE
可以是任何有效的类型名称,例如指针double*
、struct或unionstruct toto
,除了数组。由于赋值,诸如double[4]
之类的数组类型将无法工作。使用指针指向array
double(*)[4]
相反,例如,第二行又是一个
double[4]
类型的左值,在编译时检查该属性。With C99 and compound literals you can do something like
This ensures that
VALUE
is assignment compatible toTYPE
. 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 pointerdouble*
, struct or unionstruct toto
, besides arrays. Array type such asdouble[4]
wouldn't work because of the assignment. Use pointer toarray
double(*)[4]
instead, e.g as inwhere the second line again is a lvalue of type
double[4]
that is compile time checked for that property.