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

时间:2014-08-28 12:57:58

标签: c if-statement gcc-warning

使用旗帜,-pedantic -Wall -ansi,我注意到了 初始化变量f1=fopen(argv[1],"r");然后传递变量 f1 if语句中的warning: assignment makes pointer from integer without a cast [enabled by default]语句没有错误。

然而,当我在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); }

我有自己的想法,但我不确定为什么会这样。

{{1}}

我已经测试了f1和f2两种方式的初始化,并对两者都得到相同的响应。

2 个答案:

答案 0 :(得分:3)

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

相当于:

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

根据f2是否等于10分配fopen("output.txt","w")NULL

您需要的是:

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

答案 1 :(得分:3)

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

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

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