Is there any difference between these 2 versions of checking if file is actually opened:
FILE *file = fopen(fname, "rb");
if (!file)
{
exit(1);
}
And
FILE *file = fopen(fname, "rb");
if (file == NULL)
{
exit(1);
}
Both of these are equivalent.
The logical NOT operator !
is defined as follows in section 6.5.3.3p5 of the C standard:
The result of the logical negation operator
!
is 0 if the value of its operand compares unequal to 0, 1 if the value of its operand compares equal to 0. The result has typeint
. The expression!E
is equivalent to(0==E)
So !file
is the same as 0 == file
. The value 0 is considered a null pointer constant, defined in section 6.3.2.3p3:
An integer constant expression with the value 0, or such an expression cast to type
void *
, is called a null pointer constant.66) If a null pointer constant is converted to a pointer type, the resulting pointer, called a null pointer, is guaranteed to compare unequal to a pointer to any object or function66 ) The macro
NULL
is defined in <stddef.h> (and other headers) as a null pointer constant; see 7.19
This means that comparing a pointer to 0 is the same as comparing it to NULL
. So !file
and file == NULL
are the same.