Reputation:
I ran into some code I couldn't find an answer to on Google or SO. I am looking at a thread function which returns void* as you could expect. However, before the thread function ends it suddenly pulls this stunt,
return (void*) 0;
What is the purpose of that? I can't make any sense of it.
edit:
After understanding this is the same as NULL-- it is my thought they used this to skip including stdlib.
Upvotes: 0
Views: 143
Reputation: 18411
Well, I have not encountered any C++ compiler saying NULL
or 0
cannot be converted to void*
(or to/from int*
, for example). But there might be some smart compilers or static-analysis tools that would report 0 to void-pointer
conversion as a warning.
That statement is commonly found in callback implementation (like a thread-routine), which must adhere to prototype of callback being demanded (pthread_create
, CreateThread
etc). Therefore, when you implement that function, you must return the same type it was demanded for. For pthread_create
routine, you must return a void*
- and that's why return (void*)0;
is there.
Upvotes: 0
Reputation: 84735
(void*)0
is the null pointer, a.k.a. NULL
(which actually is a macro defined in several header files, e.g. stddef.h
or stdio.h
, that basically amounts to the same thing as (void*)0
).
Update:
How to explain null pointers and their usefulness? Basically, it's a special value that says, "This pointer doesn't point anywhere," or, "This pointer is not set to a valid object reference."
Historical note: Tony Hoare, who is said to have invented null references in 1965, is known to regret that invention and thus calls it his "Billion Dollar Mistake":
Whenever you work with pointers, you must make sure to never dereference a null pointer (because it doesn't reference anything by definition). If you do it anyway, you'll either get abnormal program termination, a general protection fault, or unexpected program behaviour at the very least.
Upvotes: 2