sizeof()会不会被preprocessor执行 [英] sizeof() is not executed by preprocessor

查看:344
本文介绍了sizeof()会不会被preprocessor执行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

 #如果的sizeof(INT)!= 4
/* 做一点事 */

里面使用的sizeof#如果不工作,而在的#define 它的工作原理,为什么?

 的#define尺寸(X)的sizeof(X)/ sizeof的(X [0])/ * *工作/


解决方案

没有什么是邪恶的 - 一切都可以被滥用,或在您的案件误解。在的sizeof 运营商是一个编译器的功能,但是编译器功能不可用的preprocessor(运行编译器介入之前),所以不能使用#如果 preprocessor指令。

但是,当你说:

 的#define尺寸(X)的sizeof(X)/ sizeof的(X [0])

和使用它:

 尺寸(一)

在preprocessor执行是交给编译器的文本替换:

 的sizeof(A)/ sizeof的(A [0])

#if sizeof(int) != 4
/* do something */

Using sizeof inside #if doesn't work while inside #define it works, why?

#define size(x) sizeof(x)/sizeof(x[0]) /*works*/

解决方案

Nothing is evil - everything can be misused, or in your case misunderstood. The sizeof operator is a compiler feature, but compiler features are not available to the preprocessor (which runs before the compiler gets involved), and so cannot be used in #if preprocessor directives.

However, when you say:

#define size(x) sizeof(x)/sizeof(x[0])

and use it:

size(a)

the preprocessor performs a textual substitution that is handed to the compiler:

sizeof(a)/sizeof(a[0])

这篇关于sizeof()会不会被preprocessor执行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆