C预处理器可以执行整数运算吗? [英] Can the C preprocessor perform integer arithmetic?

查看:72
本文介绍了C预处理器可以执行整数运算吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

正如问题所言, C 预处理器能够做到吗?

As the questions says, is the C preprocessor able to do it?

例如:

#define PI 3.1416
#define OP PI/100
#define OP2 PI%100

在预处理阶段是否可以计算OP和/或OP2?

Is there any way OP and/or OP2 get calculated in the preprocessing phase?

推荐答案

整数算术?运行以下程序以查找:

Integer arithmetic? Run the following program to find out:

#include "stdio.h"
int main() {
    #if 1 + 1 == 2
        printf("1+1==2\n");
    #endif
    #if 1 + 1 == 3
        printf("1+1==3\n");
    #endif
 }

答案是是,有一种方法使预处理器执行整数算术,即在预处理器条件下使用它。

Answer is "yes", there is a way to make the preprocessor perform integer arithmetic, which is to use it in a preprocessor condition.

但是请注意,您的示例不是整数算术。我刚刚检查了一下,如果您尝试让gcc进行浮点比较,它的预处理器就会失败。我还没有检查过该标准是否允许预处理器中进行浮点运算。

Note however that your examples are not integer arithmetic. I just checked, and gcc's preprocessor fails if you try to make it do float comparisons. I haven't checked whether the standard ever allows floating point arithmetic in the preprocessor.

常规宏扩展不评估整数表达式,它会留给编译器,可以通过预处理(在gcc中为-E)可以看到以下内容:

Regular macro expansion does not evaluate integer expressions, it leaves it to the compiler, as can be seen by preprocessing (-E in gcc) the following:

#define ONEPLUSONE (1 + 1)
#if ONEPLUSONE == 2
    int i = ONEPLUSONE;
#endif

结果为 int i =(1 + 1 ); (可能还有一些东西来指示源文件名和行号等)。

Result is int i = (1 + 1); (plus probably some stuff to indicate source file names and line numbers and such).

这篇关于C预处理器可以执行整数运算吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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