为什么在"if(fd = fopen(fileName,"r")= = NULL)“)中收到此警告? [英] Why am i getting this warning in "if (fd=fopen(fileName,"r") == NULL)"?

查看:209
本文介绍了为什么在"if(fd = fopen(fileName,"r")= = NULL)“)中收到此警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

FILE *fd;
if (fd=fopen(fileName,"r") == NULL)
{   
    printf("File failed to open");
    exit(1);
}

这是一个代码段.当我用gcc编译它时,出现以下警告:-

This is a code snippet. When I compile it with gcc, i get the following warning:-

warning: assignment makes pointer from integer without a cast

当我将 fd = fopen(argv [2],"r")放在方括号中时,问题得到解决..

When I put fd=fopen(argv[2],"r") within brackets, the problem gets solved..

我无法理解在未放置方括号的情况下我将整数转换为指针的位置.

推荐答案

由于运算符优先级规则,该条件被解释为fd=(fopen(fileName,"r") == NULL). ==的结果是整数,fd是一个指针,因此是错误消息.

Due to operator precedence rules the condition is interpreted as fd=(fopen(fileName,"r") == NULL). The result of == is integer, fd is a pointer, thus the error message.

考虑代码的扩展"版本:

Consider the "extended" version of your code:

FILE *fd;
int ok;
fd = fopen(fileName, "r");
ok = fd == NULL;
// ...

您希望最后一行解释为(ok = fd) == NULL还是ok = (fd == NULL)?

Would you expect the last line to be interpreted as (ok = fd) == NULL, or ok = (fd == NULL)?

这篇关于为什么在"if(fd = fopen(fileName,"r")= = NULL)“)中收到此警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆