shadyabhi
shadyabhi

Reputation: 17234

Why am i getting 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 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.

Upvotes: 5

Views: 3560

Answers (6)

Dan Kendall
Dan Kendall

Reputation: 703

Have you done the following?

#include <stdio.h>

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

Upvotes: -1

Mick
Mick

Reputation: 5197

== has a higher priority than =.

Upvotes: 1

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 798606

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

Upvotes: 2

David Schmitt
David Schmitt

Reputation: 59326

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

Upvotes: 14

Khaled Alshaya
Khaled Alshaya

Reputation: 96859

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

Upvotes: 3

Richard Pennington
Richard Pennington

Reputation: 19965

You need parenthesis around the assignment:

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

Upvotes: 1

Related Questions