This question might be too bad but I can take risk to post this question here to address my confusion.
Actually my question is that we can only assign address to pointer like :-
int *p,a;
p = &a; // OK
p = 1; // Error because you cannot assign integer literal to p*
But we can assign NULL to p like :
p = NULL;
Indeed, NULL is a macro which is value is 0 and before compiling this code by compiler it get replaced with 0 by prepocessor. So after replacement its look like
p = 0;
I know it means p is point to nothing but according to rule we can only assign address to pointer but 0 is an integer. So this isn't break the rule ?
Thanks.
you can directly set the address of a pointer in c:
Note that is not generally considered safe use of pointers for obvious reasons (can point anywhere in memory).
for more info see here and related question here
No it does not break the rule. The integer constant
0
(and generally any constant expression evaluating to 0) is treated specially and it is allowed to assign such value to a pointer. It does not mean that you can assign any integer - just zero.The current version of C++ introduces the new
nullptr
keyword which should be used instead.The reason for this is different in C from C++ IIRC. In C++
0
is special literal that, by definition, can be interpreted as a null pointer of any pointer type; so in this case there is no cast from integer to pointer. To test this you can try doing this:Which you will discover gives an error (See here for IDEOne example)
barak manos already pointed it out in his comment:
If you want to set a pointer to a literal value, you need to cast the literal value to the corresponding pointer type first.
NULL
could just as well be defined as(void *) 0
... which is implicitly convertible to any pointer type.In either case, you end up with a pointer pointing to a literal address.
In no case, however, does your pointer point to memory containing a literal
4
, though. This is, to my knowledge, not possible without assigning that literal value to anint
first:In fact literal
0
or any constant value that is zero is an exception. It could assign to a pointer and it means aNULL
ornullptr
. In reverse, any null pointer evaluates to0
.Null does not point to any memory address location, its compiler's responsibility to handle it. It is null and null is nowhere in the memory. It points to nothing.