Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
230 views
in Technique[技术] by (71.8m points)

c++ - Are C macros implicitly cast?

I've searched SO, but haven't found an answer to this specific questions. Forgive me if it's already been answered.

If you have the following:

#define MACRO  40

You don't assign it to a variable you use it in a loop:

for(int i = 0; i < MACRO; i++) {...

The perprocessor then creates:

for(int i = 0; i < 40; i++) {...

Would the compiler then implicitly cast it to an int since the comparison is with type int i? I've looked at this question Type of #define variables, and quite a few answers down Edgar Bonet implies that there is an order in which the compiler chooses how to treat the macro?

This question, How does C++ implicitly cast arguments to a comparator such as <?, was also suggested, but only describes how implicit casting works with a comparison with two types. Since a macro doesn't really have a type I'm not sure if this applies.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

In C and C++, macros are quite literally in-place replacement. The preprocessor will encounter these #defines and replace them as it finds them. That's how you can nest macros inside of macros and it only takes 1 pass to preprocess.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...