奇怪的宏定义问题 [英] Weird macro definition issue

查看:67
本文介绍了奇怪的宏定义问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在编译时根据另一个宏的值定义一个宏。但是,此代码未按预期执行:

I want to define a macro at compile time based on the value of another macro. However this code is not executing as expected:

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define SIXTEEN 16
#define TWO (SIXTEEN % 8 == 0)? (SIXTEEN / 8) : ((SIXTEEN / 8) + 1)

int main();

int main() {
    printf("max = %d\n", TWO);
    int i;
    for (i = 0; i < TWO; i++) {
        printf("%d\n", i);
    }
    return 0;
}

此打印:

max = 2
0
1
2
...

并持续到终止时,应该简单地打印:

and continues until terminated, When it should be printing simply:

max = 2
0
1

并退出。

如果我这样做,它会起作用:

If I do this instead, it works:

#define TWO 2

我认为这是宏定义的问题...但是,如果我对原来的#define,它似乎可以正常工作:

I thought that this was an issue with the macro's definition... however, if I do the following with the original #define, it seems to work:

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

有人可以解释这里发生了什么吗?

Can anyone explain what's going on here?

推荐答案

问题是令牌两个被定义宏的令牌所代替,因此:

The problem is that the token TWO is replaced by the tokens with which you defined the macro, so this:

i < TWO

变为:

i < (SIXTEEN % 8 == 0)? (SIXTEEN / 8) : ((SIXTEEN / 8) + 1) 

由于运算符优先级,因此读取为:

Because of operator precedence, this is read as:

(i < (SIXTEEN % 8 == 0))
    ? (SIXTEEN / 8) 
    : ((SIXTEEN / 8) + 1) 

您需要多余的括号,这样当两个被其替换列表替换时,您会得到想要的结果:

You need extra parentheses so that when TWO is replaced by its replacement list, you get the result you want:

#define TWO ((SIXTEEN % 8 == 0)? (SIXTEEN / 8) : ((SIXTEEN / 8) + 1))
            ^                                                       ^

使用宏时,最好在任何可能的地方使用括号以确保结果是您期望的。

When using macros, it's best to use parentheses wherever you can to ensure the result is what you expect.

这篇关于奇怪的宏定义问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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