In a lot of c code snippets i see (void *)0,what does casting an integer with a pointer mean?
1 Answer
In general, casting an integer to a pointer "means" creating a pointer value pointing to that exact numeric address in memory. But I have put the word "means" in quotes here, because the actual meaning is more complicated.
There are basically three subcases.
- If the integer is the constant 0 (and especially if the casted-to pointer type is
void *), this is a null pointer constant. By definition, it is the syntactic construct that gets you a null pointer value. By definition, a null pointer points nowhere (it "compares unequal to the pointer to any actual object"). - In old-school C programming, and to this day in embedded C programming, if the integer is nonzero, it's an actual memory address you're trying to access.
- In modern, portable, high-level C programming, and especially here on Stack Overflow, the meaning is implementation-defined at best or undefined at worst, meaning that you shouldn't do it and you probably shouldn't even ask about it, since no one can say for sure what it means.
In answer to your comment in response to Jonathan Leffler's, NULL is not actually a keyword, but rather a preprocessor macro which expands to either (void *)0 or, maybe, plain 0. (How it is that it's possible for a plain 0, without a cast, to work properly as a null pointer constant is a fascinating but frequently badly misunderstood side question which I am not going to go into here. See section 5 in the C FAQ list if curious.)
1 Comment
((void*)0) but not to (void*)0. See N1570 7.1.2p5, which requires definitions of object-like macros to be protected by parentheses when necessary.
(void *)0is a way of writing a null pointer constant; so isNULLand in many contexts0will also be converted to a null pointer constant if needed (and there are other ways of writing such pointers). If the value being cast is not zero, then it has a different purpose, and is generally less portable (meaning, not at all portable).(void *)0inttovoid *or vice versa?) doesn't mention(void *)0which does have a portable and sensible meaning. The duplicate was discussing(void *)5and similar casts, primarily in the context of the 'data' argument topthread_create(), which is a rather specialized (ab)use of casting an integer to a void pointer.\(void *)0is another way of writingNULL, butNULLis not a keyword — it is just a macro defined when you include any of half-a-dozen standard C headers (<locale.h>,<stddef.h>,<stdio.h>,<stdlib.h>,<string.h>,<time.h>).