繁体   English   中英

C 预处理器中的 SIGN 宏

[英]SIGN Macro in C preprocessor

我尝试编写一个 SIGN 宏,它返回 - 或 +。

但是它不像我预期的那样工作,有人知道怎么做吗?

#include <stdio.h>
#define ABS(x) (((x) < 0) ? (-(x)) : (x))
#define MAX(x,y) (((x) < y) ? (y) : (x)
#define MIN(x,y) (((x) < y) ? (x) : (y))
#define DIFF(x,y) (ABS(x-y))
#define SIGN(x) (((x) < 0) ? (-) : (+))

int main(){

  int i = -45;
  int j = -5;
  printf("%c\n", SIGN(i) );

  return 0;
}

所有其他宏都可以工作,但是使用 SIGN 我得到一个错误

“错误:')' 标记前的预期表达式 #define SIGN(x) (((x) < 0) ? (-) : (+))”

有两种可能的版本:

  • #define SIGN(x) ( (x) < 0 ? '-' : '+' )
    这是天真的解决方案。 它返回一个对应于字符'-''+'int 它不能正确处理零。 对于初学者来说,它可能很好。

  • #define SIGN(x) ( "+- "[((x)<=0) + !(x)] )
    这是过度设计的解决方案。 它返回一个值为'-''+'char ,或者在零的情况下返回一个空格' ' 它根据这个真值表使用布尔运算:

     x x<=0 !x pos false false neg true false 0 true true

    将两个布尔表达式的结果相加得到值 0、1 或 2,然后将其用作字符串文字"+- "中的查找索引。 例子:

     #include <stdio.h> #define SIGN(x) ( "+- "[((x)<=0) + !(x)] ) int main (void) { int a = -123; int b = +123; int c = 0; printf("%c\\n", SIGN(a)); printf("%c\\n", SIGN(b)); printf("%c\\n", SIGN(c)); }
#define SIGN(x) (((x) < 0) ? ('-') : ('+'))

printf("%c\n", SIGN(i) );  // Will print either - or + followed by NewLine(\n)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM