代码之家  ›  专栏  ›  技术社区  ›  Spidfire

在C中定义宏不起作用

  •  1
  • Spidfire  · 技术社区  · 15 年前

    我试着在C语言中创建一个宏来判断字符是否是十六进制数(0-9A-Z A-Z)

    #define _hex(x) (((x) >= "0" && (x) <= "9" )||( (x) >= "a" && (x) <= "z") || ((x) >= "A" && (x) <= "Z") ? "true" : "false")
    

    这是我想出来的,但这样的循环不行

    char a;
         for(a = "a" ; a < "z";a++){
            printf("%s  => %s",a, _hex(a));
         }
    

    它会出错

    test.c:8: warning: assignment makes integer from pointer without a cast
    test.c:8: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    test.c:9: warning: comparison between pointer and integer
    
    5 回复  |  直到 15 年前
        1
  •  9
  •   viraptor    15 年前

    “a”是指向字符串“a”的指针。您需要将字符与“a”进行比较。

    #define _hex(x) (((x) >= '0' && (x) <= '9' )||( (x) >= 'a' && (x) <= 'z') || ((x) >= 'A' && (x) <= 'Z') ? "true" : "false")
    

    但你也可以用 isalnum(x) 相反-如果字符是数字或字符,则返回true。

    isxdigit(x) 如果这真的是一张十六进制支票的话。

        2
  •  2
  •   Dinah SLaks    15 年前

    使用 isxdigit() 然后。

        3
  •  1
  •   Clifford    15 年前

    您在测试循环中所犯的错误与在宏中所犯的错误相同。

    for(a = "a" ; a < "z";a++){
    

    应该是:

    for(a = 'a' ; a < 'z'; a++){
    

    当然,明智的解决办法是 isxdigit() 定义于 ctype.h 作为一个宏(如果你感兴趣的话,你可以看看)。

        4
  •  0
  •   sizzzzlerz    15 年前

    您还需要将“for”循环更改为在“a”到“z”范围内循环,而不是在“a”到“z”范围内循环。

        5
  •  0
  •   Artyom    15 年前

    我建议不要对这些函数使用宏。C99支持内联函数只需编写

    inline char *_hex(char c)
    {
       ... write there what you need in readable form ...
    }