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

大憨熊 提交于 2019-12-17 14:01:10

问题


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

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

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

I am not able to understand where am i converting integer to pointer when the brackets are not put.


回答1:


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)?




回答2:


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);
}



回答3:


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




回答4:


You need parenthesis around the assignment:

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



回答5:


== has a higher priority than =.




回答6:


Have you done the following?

#include <stdio.h>

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



来源:https://stackoverflow.com/questions/2117699/why-am-i-getting-this-warning-in-if-fd-fopenfilename-r-null

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