什么时候可以返回NULL作为C函数的返回值? [英] When are you able to return NULL as the returning value of a C function?
问题描述
我想知道是否可以告诉我何时可以返回NULL
,这是C函数的结果.
I was wondering if you could tell me when you are able to return NULL
, as the result of a function in C.
例如int lenght()
不能返回NULL
,因为它在return语句中期望int
.
For instance int lenght()
can't return NULL
because is is expecting an int
in the return statement.
但是函数struct node* find(int key)
在使用链表时允许我返回NULL.
But the function struct node* find(int key)
, when working with linked lists allows me to return NULL.
推荐答案
NULL
是一个指针值-或更确切地说是一个空指针值.
NULL
is a pointer value - or rather a null-pointer value.
NULL
表示该函数找不到指针应指向的位置-例如,如果您要打开文件,但不起作用,文件指针将以NULL
的形式返回.因此,您可以测试指针的值并检查它是否起作用.
NULL
means that the function can't find where your pointer should point to - for example if you want to open a file, but it doesn't work your file pointer is returned as NULL
. So you can test the value of a pointer and check to see if it worked or not.
如果您正在编写例程
int length()
然后,如果length无法读取所发送内容的长度,则可以返回负值-这是一种指示错误的方式,因为通常length永远不会为负....
then you could return a negative value if length is unable to read the length of whatever you send it - this would be a way of indicating an error, because normally lengths can never be negative....
这篇关于什么时候可以返回NULL作为C函数的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!