繁体   English   中英

为什么我在“if(fd = fopen(fileName,”r“)== NULL)”中收到此警告?

[英]Why am i getting this warning in “if (fd=fopen(fileName,”r“) == NULL)”?

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

这是一段代码片段。 当我用gcc编译它时,我得到以下警告: -

warning: assignment makes pointer from integer without a cast

当我把fd = fopen(argv [2],“r”)放在括号内时,问题就解决了。

当没有放置括号时,我无法理解将整数转换为指针的位置。

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

考虑代码的“扩展”版本:

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

你期望最后一行被解释为(ok = fd) == NULL ,还是ok = (fd == NULL)

等于运算符的优先级高于赋值运算符。 只需将您的代码更改为:

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

==具有比=更高的优先级,因此它将fopen()的结果与NULL进行比较,然后将其分配给fd

你需要围绕作业括号:

if ((fd=fopen(fileName,"r")) == NULL)
....

==的优先级高于=。

你做过以下的事吗?

#include <stdio.h>

如果没有这个,编译器会假定所有函数都返回一个int

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM