Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在C中正确使用#if指令?_C_C Preprocessor_Conditional Compilation - Fatal编程技术网

在C中正确使用#if指令?

在C中正确使用#if指令?,c,c-preprocessor,conditional-compilation,C,C Preprocessor,Conditional Compilation,C预处理器指令#if的以下结构运行良好 #define C 1 #if C==1 ... #endif 但我想用这样的方式: #define REAL double #if REAL==double ... #elif REAL==float ... #else assert(0); #endif 这是无效的。有解决办法吗 有解决办法吗 有很多方法可以将宏扩展与条件编译结合起来。目前还不清楚你们中的哪一个会考虑解决方案,但这里有一个可能性: #define doubledoubl

C预处理器指令
#if
的以下结构运行良好

#define C  1

#if C==1
...
#endif
但我想用这样的方式:

#define REAL double

#if REAL==double
...
#elif REAL==float
...
#else
   assert(0);
#endif
这是无效的。有解决办法吗

有解决办法吗

有很多方法可以将宏扩展与条件编译结合起来。目前还不清楚你们中的哪一个会考虑解决方案,但这里有一个可能性:

#define doubledouble 1
#define floatfloat 1

#define concat_literal(x,y) x ## y
#define realtype(t1,t2) concat_literal(t1,t2)

// ...

#define REAL float

#if realtype(REAL, double)
    // REAL is double
#elif realtype(REAL, float)
    // REAL is float
#else
    // REAL is something else
#endif
realtype
宏通过宏扩展其参数并将它们连接在一起来工作。在重新扫描时,如果结果是
doubledouble
floatfloat
,则该结果将进一步扩展为1。如果该标识符未定义为宏名称,则
#If
将其视为0


当然,这不是万无一失的。如果
REAL
具有多令牌扩展,例如
long double
,则它不起作用。与其他定义的宏名称发生冲突的风险也很小。

这个答案可能会有所帮助:
有解决方案吗?
解决方案?对我来说,这似乎是一个XY问题-您正在使用
#if
选择一些与类型相关的代码-您试图解决的真正问题是什么?为什么不直接编写
REAL a=1
并忘掉它呢?@KamilCuk,我想在代码中声明实数变量,如下所示:
REAL r1,r2realr1,r2所以只要这样做,它应该与您显示的代码一起工作。。无论如何,为什么不
typedef
typedef双实数
也可以<代码>我找到了另一种方法。
那么这个问题是否应该结束?不需要-只需包含在本例中。创建
REAL
类型的公共抽象/接口,并使用单个代码流,而不是多个代码流,这样会更简洁。