Reputation: 36611
What is the difference between
int* a = 0;
and
int* a = 10;
?
Upvotes: 3
Views: 2737
Reputation: 24577
First, these are not expressions, they're declarations.
int* a = 0;
This declares a pointer-to-integer and initializes it with a zero compile-time integer constant, which is transformed into a null pointer value. In other words, it declares a null pointer to integer.
int* a = 10;
This declares a pointer-to-integer that points to whatever your specific compiler defines to be at the address represented by the integer 10. In the vast majority of cases, there's nothing there, so you end up with undefined behavior by merely declaring this pointer.
Upvotes: 4
Reputation: 75399
One of these should trigger a warning. Crank up your compiler warnings!
int *a = 0;
This one is okay. It declares a pointer a
to an int
and initializes it to 0, or the NULL
pointer, which means it points to nothing. Attempting to dereference it will lead to bad things, but you can check whether or not a pointer is valid before you dereference it, so NULL
pointers are actually good things.
int *a = 10;
This is not okay. It declares the same pointer to an int
but initializes it to 10. First, the compiler will complain that the int
10 can't be implicitly cast to a pointer type. If you ignore this, the pointer points to memory location 10, which you have no guarantee is a valid int
or a valid anything or even belongs to your process. Dereferencing a
will be bad, just like dereferencing a
when it was NULL
, but what's worse, we have no way to check the validity of a
because 10 could be good or bad - we have no way of knowing until we use it and get what we want/garbage/nasal demons.
Upvotes: 6
Reputation: 26060
int* a
declares variable a
as a pointer to integer.
=0
and =10
assign some value to the variable.
Note that a
is a pointer, its value is supposed to be an address.
Address 0
has a particular meaning: it's NULL
, represent an empty pointer.
Address 10
has no meaning: it's a random memory address. Since it's not NULL
, most functions will consider it a valid address, will dereference it, and thus it will create problems (undefined behavior) to your application.
Upvotes: 10
Reputation: 1109
Here we are asigning value to pointer, int* a = 0; means int a* = NULL; However, in c++, int* a = 10 wont compile, because "Conversion from integral type to pointer type requires reinterpret_cast, C-style cast or function-style cast", as compiler thinks 10 is integral type not a pointer.
Upvotes: 1
Reputation: 6656
int* a = 0;
Assign 0 to the pointer.
int* a = 10;
Assigns 10 to the pointer. Note, to the pointer (i.e. the variable which should contain an address) not the pointee!
That last one is dangerous, as it defeats NULL
pointer checks.
Upvotes: 4