睿宏 陳
PRO
last month
睿宏country asked

fptr is a location, and NULL is a return value, then why can we write fptr == NULL? Also, so does it mean that the function fopen returns a location?

Udayan Shakya
Expert
last month
Udayan Shakya answered

When you use fptr == NULL, you're actually checking if fptr is equal to the special value NULL, which indicates that no file was opened successfully at that pointer.

Basically, fopen() is designed to either:

  • return a pointer to a FILE object representing the file you want to work with,

  • or, if there's an error (like if the file isn't found), it returns NULL.

  • The value NULL in this context signals that the pointer fptr doesn't point to any valid file, allowing you to safely check if the file operation succeeded.

In other words, NULL isn't just an ordinary value; it's actually a special marker that's treated differently from ordinary literals such as 1, 0, "yes", "no", etc.

That's why you can indeed check fptr == NULL but can't do checks such as fptr == "yes" since that's not allowed in pointer operations.

Hope this helps you understand the behavior of NULL and pointers better! Let me know if you have any more questions.

C
This question was asked as part of the Learn C Programming course.