3

I have found in some code NULL pointer is defined as follows -

#define NULL ((char *)0)

I found these code compiles fine. But I did not understand how this works. Can anyone please explain how 0 is casted to a char pointer?

And is it valid to use it as a FILE pointer making null -

FILE *fp = NULL;
9
  • 4
    It works...poorly (in fact, I don't think it's allowed). You want ((void *)0) instead. As to how it works: the standard defines a conversion from an integer constant with the value 0 to a pointer, and specifies that the result will always be a null pointer. Commented Mar 31, 2015 at 22:30
  • @Jerry Coffin, yes you are right. While compiling the code I found the code compiles without any error but with the following warning - warning: "NULL" redefined [enabled by default] /usr/lib/gcc/i686-linux-gnu/4.6/include/stddef.h:402:0: note: this is the location of the previous definition But I did not understand how this works. Commented Mar 31, 2015 at 22:33
  • 1
    I think this question is already answered here: stackoverflow.com/questions/1296843/… Commented Mar 31, 2015 at 22:35
  • Once upon a long time ago, that was the normal way to write NULL; we are talking about in the 1980s here, before there was a standard and before void * was uniformly supported. When the C standard was published (1989. 1990), it became less appropriate; it should be a ((void *)0) instead. Maybe your code is old enough that it is using the pre-standard definition. Commented Mar 31, 2015 at 22:47
  • ((char *)0) is not a valid null pointer constant (in C since the 1989 ANSI standard) and therefore not a valid definition for NULL. Given that definition, FILE *fp = NULL; is a constraint violation, requiring a compile-time diagnostic (and perhaps rejecting the program). Commented Mar 31, 2015 at 22:51

1 Answer 1

1

The C library Macro NULL is the value of a null pointer constant.It may be defined as ((void*)0), 0 or 0L depending on the compiler vendor. Depending on compiler,declaration of NULL can be

#define NULL ((char *)0)

or

#define NULL 0L

or

#define NULL 0

And is it valid to use it as a FILE pointer making null--> Yes.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.