c语言中的null
Several programming languages make use of the concept of null.
几种编程语言都使用null的概念。
Go has nil
, JavaScript has null
, Python has None
, and so on.
Go具有nil
,JavaScript具有null
,Python具有None
,依此类推。
C has NULL
.
C具有NULL
。
NULL however is used differently from other languages. In C, NULL is limited to identifying a null pointer.
但是,NULL与其他语言的用法不同。 在C中,NULL限于标识空指针 。
When we initialize a pointer, we might not always know what it points to. That’s when it is useful:
当我们初始化一个指针时,我们可能并不总是知道它指向什么。 那是有用的时候:
int * p_some_variable = NULL;
NULL
is not available by default: you need to include stdio.h
to use it (or if you prefer, stddef.h
:
NULL
默认情况下不可用:您需要包括stdio.h
才能使用它(或者,如果您愿意,可以使用stddef.h
:
#include <stdio.h>
int main(void) {
int * p_some_variable = NULL;
}
Otherwise the C compiler will give you an error:
否则,C编译器会给您一个错误:
hello.c:3:26: error: use of undeclared identifier
'NULL'
int * p_some_variable = NULL;
^
1 error generated.
You can check if a pointer is a null pointer by comparing it to NULL
:
您可以通过将其与NULL
比较来检查指针是否为空指针:
#include <stdio.h>
int main(void) {
int * p_some_variable = NULL;
if (p_some_variable == NULL) {
printf("equal");
}
}
In practice, NULL
is a constant equivalent to 0
, or "\0"
.
实际上, NULL
是等于0
或"\0"
的常数。
This is why you can set a string to NULL using:
这就是为什么可以使用以下命令将字符串设置为NULL的原因:
char *a_string = '\0';
c语言中的null