5
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.

shadyabhi
  • 16,675
  • 26
  • 80
  • 131

6 Answers6

14

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

David Schmitt
  • 58,259
  • 26
  • 121
  • 165
3

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);
}
Khaled Alshaya
  • 94,250
  • 39
  • 176
  • 234
2

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

Ignacio Vazquez-Abrams
  • 776,304
  • 153
  • 1,341
  • 1,358
1

You need parenthesis around the assignment:

if ((fd=fopen(fileName,"r")) == NULL)
....
Richard Pennington
  • 19,673
  • 4
  • 43
  • 72
1

== has a higher priority than =.

Mick
  • 4,987
  • 1
  • 19
  • 23
-1

Have you done the following?

#include <stdio.h>

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

Dan Kendall
  • 702
  • 5
  • 22
  • mark downs with no comments? Bad form ppl. Help me to learn from my error. Also note - it was a question, not an assertion. – Dan Kendall Jan 22 '10 at 15:02