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

跟風遠走 提交于 2019-11-27 15:43:08

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;
// ...

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

The precedence of the equality operator is higher than the assignment operator. Just change your code to:

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

== has higher precedence than =, so it compares the result of fopen() to NULL, then assigns that to fd.

You need parenthesis around the assignment:

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

== has a higher priority than =.

Dan Kendall

Have you done the following?

#include <stdio.h>

Without this, the compiler assumes all functions return an int.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!