Home > database >  Difference between if (!file) and if (file == NULL)
Difference between if (!file) and if (file == NULL)

Time:12-15

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

CodePudding user response:

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 type int. 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 function

66 ) 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.

CodePudding user response:

https://github.com/gcc-mirror/gcc/blob/master/gcc/ginclude/stddef.h

<stddef.h> defines NULL as literally 0.

What makes a conditional statement in C be 'true', is that it is not 0. That is it.

The ! operator converts non-zero values to 0, and 0 values to 1. The == operator returns 1 if the operands are equal and 0 otherwise.

Your two statements are logically equivalent. (probably) The only difference is style or personal preference. You might find it interesting to look at the compiled assembly to dig deeper.

  • Related