Reputation: 243
Whats the difference between integer and the address returned by &
?
Therefore, why should I type-cast integer to an integer pointer when assigning it to an integer pointer?
Upvotes: 1
Views: 2772
Reputation: 1254
Whats the difference between integer and the address returned by & ?
I think this question has already been answered in the comments. The difference is the type of those variables. Basically int
= Integer type and *int
= Pointer type.
Furthermore: Conversion from pointer
to int
can result in undefined behavior.
Therefore, why should I type-cast integer to an integer pointer when assigning it to an integer pointer?
Because the standard says:
C99 Section 6.5.4 and 6.5.16.1:
Conversions that involve pointers, other than where permitted by the constraints of 6.5.16.1, shall be specified by means of an explicit cast.
And C++ Section 5.4:
Any type conversion not mentioned below and not explicitly defined by the user (12.3) is ill-formed.
Upvotes: 0
Reputation: 16049
Integer and pointer to integer are different types.
Given your example:
int value = 5;
int address = &value;
value
is variable of type int
.&value
returns address of type int*
address = &value
tries to assign int*
to int
.While integers can be converted to pointers and back, it doesn't mean that addresses are necessarily integer values.
Just like you can assign double
to int
, you can assign int *
to int
. But it's not necessarily what you want, and that's why compiler warns about it.
In fact, unless you are working very close to hardware (writing driver for example), it's very unlikely you need to do conversions between integers and pointers.
Correct way to do this, without needing any casts:
int * pointer = &value;
Upvotes: 3