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

发布于 2024-08-18 10:04:31 字数 371 浏览 4 评论 0原文

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") 放在括号内时,问题得到解决..

我无法了解当未放置括号时我在哪里将整数转换为指针

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.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(6

﹂绝世的画 2024-08-25 10:04:31

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

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

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

您是否希望最后一行被解释为 (ok = fd) == NULLok = (fd == NULL)代码>?

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

倾听心声的旋律 2024-08-25 10:04:31

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

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

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);
}
私藏温柔 2024-08-25 10:04:31

== 的优先级高于 =,因此它将 fopen() 的结果与 NULL 进行比较,然后赋值到fd

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

玻璃人 2024-08-25 10:04:31

您需要在作业周围加上括号:

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

You need parenthesis around the assignment:

if ((fd=fopen(fileName,"r")) == NULL)
....
苯莒 2024-08-25 10:04:31

== 的优先级高于=。

== has a higher priority than =.

挽心 2024-08-25 10:04:31

您是否做到了以下几点?

#include <stdio.h>

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

Have you done the following?

#include <stdio.h>

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文