Why NULL is not predefined by the compiler

This problem bothered me for a while. I have never seen another definition of NULL, it is always

#define NULL  ((void *) 0)

Is there any architecture where NULL is defined differently, and if so, why doesn't the compiler declare this for us?

+5
source share
4 answers

C 2011 Standard, online project

6.3.2.3
...
3 0 , void *, . 66) , , , .
66) NULL <stddef.h> ( ) ; . 7.19.

NULL ; 0 0, void *, , 0. , NULL 0.

, (0, NULL ..) , , 0-,

+3

WhozCraig , ( , ). :

: AS/400 - , NULL. , , . "" 128- ( 128- ), "", . , int *p = (int *)1; if (p) { printf("foo"); } "foo" . , p, , , "" NULL.

, . 16- . . "", , NULL. malloc, math .. , . , , .


- ( - ), , WhozCraig .

, .

, #define NULL ((void *)0) ; 0, - 0L 0ULL , . ++ ((void *)0) ; , , ++, void.

C , char * int * . void *, , malloc() (char *malloc(); - ), . C ( , ICL Perq - Three Rivers - ).

+4

ANSI-C K & R C , . , "". , ... , CDC ( , ).

 if ( NULL != ptr )     /* like this */
 if ( ptr )             /* never like this */

, , "", , 0xFFFF . , .

+1

I do not know the answer to this, but I think. In C, you usually do a lot of mallocs and therefore a lot of tests for returned pointers. Since malloc returns void *, and especially (void *) 0 after a failure, NULL is a natural thing to determine in order to verify the success of malloc. Since this is so important, other library functions also use NULL (or (void *) 0), such as fopen. In fact, everything the pointer returns.

Therefore, there is no reason to define this at the language level - it is simply a special pointer value that can be returned by so many functions.

0
source

All Articles