-D name = definition和bitwise运算符

问题描述 投票:1回答:2

我试图了解下一次计算是如何执行的。

例如,如果这是我的终端命令

gcc ex2.c -D b+=2

为什么我得到5?

#include <stdio.h>

int main() 
{
#ifdef b
    printf("%d\n", 2 b | ~ 2 b);
#endif
    return 0;
}

2 b表示2 * b?

~2 b意味着2 * b然后〜?

c gcc bitwise-operators bitflags
2个回答
4
投票

gcc ex2.c -D b+=2编译定义b为+2所以来源

#include <stdio.h>

int main() 
{
#ifdef b
    printf("%d\n", 2 b | ~ 2 b);
#endif
    return 0;
}

就好像

#include <stdio.h>

int main()
{

    printf("%d\n", 2 + 2 | ~ 2 + 2);

    return 0;
}

对我来说,打印-1


要在预处理后查看结果,请使用选项-E:

/tmp % gcc ex2.c -E -D b+=2
<command-line>: warning: missing whitespace after the macro name
...
# 2 "ex2.c" 2

int main()
{

    printf("%d\n", 2 + 2 | ~ 2 + 2);

    return 0;
}

7
投票

这很奇怪,它可以工作,看起来像gccclang在解析命令行参数时的bug(或特性)。

看起来像gcc用空格代替宏观声明中的第一个=标志。所以参数:

-D b+=2

等于

#define b+ 2

因为gcc有一个扩展来解释它,它等于

#define b + 2

这使得预处理器输出:

printf("%d\n", 2 + 2 | ~ 2 + 2);

表达式2 + 2 | ~ 2 + 2等于(2 + 2) | ((~ 2) + 2)(见operator precedence),它在twos complement系统上等于4 | (-3 + 2),等于4 | -1。在二重补充-1等于0xff....ff所以4 | -1等于0xff...ff(因为它是二元OR),这是-1

© www.soinside.com 2019 - 2024. All rights reserved.