When creating a file pointer should I initialize it to NULL or should I leave it uninitialized?

I currently have FILE* img;. I think the better practice is to have FILE* img = NULL; so it it doesn't store a garbage value. However, I seem to get an error when doing this.

Any thoughts?


FILE* img;    

while (fread(&buffer, BLOCK, 1, inptr) != 0) 
    // do stuff
    if (beginning of file)
        img = fopen(title, "a");

1 Answer 1


I always prefer doing what I need to do. no more and no less. for example

int i;

if (condition)
    i = 10;
    i = 20;

I wouldn't bother unnecessarily initialize i here, assuming condition does not involve i of course, since it's initialized anyway in either the if or the else branch.

on the other hand,

int i = 10;

for (int j = 0; j < 5; j++)
    i += 2;

I indeed would initialize i here since not initializing it could cause problems.

so the answer to your question is: if you want your variable to have a certain value at some point, then have this value assigned to it so that it has it at this point.

  • Thanks @Kareem. I edited my comment to better show what I have in my code. I didn't want to initalize img to fopen(title, "a") outside of my loop because I didn't want an empty file if the while condition returned 0. I would open and close that file with nothing in it.
    – user2137
    Jun 9, 2015 at 14:58
  • @mECH so wasn't the answer clear enough or do you want me to tell you what exactly to do in this situation?
    – kzidane
    Jun 9, 2015 at 15:03
  • No, it's clear enough. I wanted to give more detail to my post for people who may have the same question.
    – user2137
    Jun 9, 2015 at 15:11
  • @mECH I didn't notice you getting an error by the way. what was it?
    – kzidane
    Jun 9, 2015 at 15:35

You must log in to answer this question.