gpt4 book ai didi

c - 通过条件读取 #define 中的空指针

转载 作者:行者123 更新时间:2023-11-30 16:48:07 24 4
gpt4 key购买 nike

我有宏printerr的定义

#define CLR_R "\x1b[1;31m" 
#define CLR_N "\x1b[0m"
#define printerr(caller,msg) (caller==NULL)?printf(CLR_R "%s" CLR_N "\n",msg) \
: printf(CLR_R "%s:" CLR_N " %s\n",caller,msg)

并收到警告

warning: reading through null pointer (argument 2), when calling printerr(NULL,"error");.

如何抑制此警告?

#include <stdio.h>
#define printerr(caller,msg) (caller==NULL)?printf("%s\n",msg) : \
printf("%s: %s\n",caller,msg)
void main() {
printerr("Error","error occurred"); //will be ok
printerr(NULL,"error"); //Warning: is caller even checked here?
}

最佳答案

这有效(gcc,clang):

#include <stdio.h>
int main()
{
#define CLR_R "\x1b[1;31m"
#define CLR_N "\x1b[0m"

#define printerr(caller,msg) \
(caller==NULL)? printf(CLR_R "%s" CLR_N "\n",msg) : \
printf(CLR_R "%s:" CLR_N " %s\n", ((caller)?(caller):""),msg)


printerr(NULL,"msg");
printerr("caller","msg");
}

我正在使用 ((caller)?(caller):"") 来抑制警告。它永远不会计算为 ""

您还可以使用内联函数达到相同的效果:

#define CLR_R "\x1b[1;31m" 
#define CLR_N "\x1b[0m"
static inline int inl_printerr(char const *caller, char const *msg)
{
if (caller)
return printf(CLR_R "%s:" CLR_N " %s\n", caller,msg);
else
return printf(CLR_R "%s" CLR_N "\n",msg);
}

(推荐,因为它避免了宏所存在的类型安全和双重计算问题)。

关于c - 通过条件读取 #define 中的空指针,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43100020/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com