为什么我在“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") 放在括号内时,问题得到解决..
我无法了解当未放置括号时我在哪里将整数转换为指针。
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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
由于运算符优先级规则,条件被解释为
fd=(fopen(fileName,"r") == NULL)
。==
的结果是整数,fd
是一个指针,因此是错误消息。考虑代码的“扩展”版本:
您是否希望最后一行被解释为
(ok = fd) == NULL
或ok = (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:
Would you expect the last line to be interpreted as
(ok = fd) == NULL
, orok = (fd == NULL)
?等号运算符的优先级高于赋值运算符。只需将您的代码更改为:
The precedence of the equality operator is higher than the assignment operator. Just change your code to:
==
的优先级高于=
,因此它将fopen()
的结果与NULL
进行比较,然后赋值到fd
。==
has higher precedence than=
, so it compares the result offopen()
toNULL
, then assigns that tofd
.您需要在作业周围加上括号:
You need parenthesis around the assignment:
== 的优先级高于=。
== has a higher priority than =.
您是否做到了以下几点?
如果没有这个,编译器会假设所有函数都返回一个
int
。Have you done the following?
Without this, the compiler assumes all functions return an
int
.