Why do I get this warning in "if (fd = fopen (fileName," r ") == NULL) ??

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

This is a piece of code. When I compile it with gcc, I get the following warning: -

 warning: assignment makes pointer from integer without a cast 

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

I cannot figure out where I convert an integer to a pointer when the brackets do not fit.

+4
source share
6 answers

Due to operator precedence rules, the condition is interpreted as fd=(fopen(fileName,"r") == NULL) . The result == is an integer, fd is a pointer, so an error message.

Consider the "extended" version of your code:

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

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

+13
source

The priority 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
source

You need to copy around the job:

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

== takes precedence over = , so it compares the result of fopen() with NULL , then assigns it to fd .

+1
source

== has higher priority than =.

+1
source

Have you done the following?

 #include <stdio.h> 

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

-one
source

Source: https://habr.com/ru/post/1299109/


All Articles