gpt4 book ai didi

在 if 中初始化变量时发出警告

转载 作者:太空宇宙 更新时间:2023-11-04 00:49:13 25 4
gpt4 key购买 nike

使用标志,-pedantic -Wall -ansi,我注意到当我初始化一个变量 f1=fopen(argv[1],"r"); 然后传递变量f1if 语句中,它这样做没有错误。

然而,当我在 if 语句中初始化变量时,它会抛出警告:

警告:赋值从整数生成指针而不进行强制转换[默认启用]

我有我的想法,但不确定这是为什么。

FILE *f1;
FILE *f2;
f1=fopen(argv[1],"r");

if(f1==NULL)
{
fprintf(stderr,"unable to open file - %s\n",f1);
}
if(f2=fopen("output.txt","w")==NULL) /*throws warning*/
{
fprintf(stderr,"unable to open file - %s\n",f2);
}

我已经测试了 f1 和 f2 以两种方式进行初始化并得到了相同的响应。

最佳答案

if(f2=fopen("output.txt","w")==NULL)

== 的优先级高于 =,因此您实际上是在将 bool 值(C90 中的 int)存储在指针。添加一些括号:

if((f2 = fopen("output.txt","w")) == NULL)

关于在 if 中初始化变量时发出警告,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25549402/

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