Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NULL in C grammar

Tags:

c

grammar

I was wondering how NULL could be characterized in a C grammar, will it be a constant?

like image 819
user1479589 Avatar asked Jan 21 '26 03:01

user1479589


2 Answers

NULL is a macro object defined in some standard header <stddef.h>. On my Debian/Sid/x86-64 system with GCC 4.8 it is defined as follow (lines 394 and following of the compiler specific /usr/lib/gcc/x86_64-linux-gnu/4.8/include/stddef.h header file)

 /* A null pointer constant.  */

 #if defined (_STDDEF_H) || defined (__need_NULL)
 #undef NULL             /* in case <stdio.h> has defined it. */
 #ifdef __GNUG__
 #define NULL __null
 #else   /* G++ */
 #ifndef __cplusplus
 #define NULL ((void *)0)
 #else   /* C++ */
 #define NULL 0
 #endif  /* C++ */
 #endif  /* G++ */
 #endif  /* NULL not defined and <stddef.h> or need NULL.  */
 #undef  __need_NULL

BTW, a pointer which has been dereferenced is known to not be the null pointer value. In other words, GCC is permitted to optimize (assuming p has been declared as int *p;)

  int x= *p;
  if (!p) do_very_complex_stuff(); 
  // or: if (p == NULL) do_very_complex_stuff(); 

as simply

  int x= *p;

at least outside of freestanding programs.

IIRC, that optimization made a harsh debate between Linus Torvalds and some GCC developers.

Pedantically the NULL pointer (i.e. the null pointer value) is perhaps not required to be all-zero bits, but I don't know any implementation doing that today.

like image 191
Basile Starynkevitch Avatar answered Jan 23 '26 21:01

Basile Starynkevitch


NULL is not part of C grammar. NULL is #defined in stddef.h standard header.

like image 29
Jean-Baptiste Yunès Avatar answered Jan 23 '26 20:01

Jean-Baptiste Yunès