Alan Salios
Alan Salios

Reputation: 243

Difference between address of a variable and integer

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

Answers (2)

Sambuca
Sambuca

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

user694733
user694733

Reputation: 16049

Integer and pointer to integer are different types.

  • Integer variable holds integer value.
  • Pointer variable holds address value.

Given your example:

int value = 5;
int address = &value;
  1. value is variable of type int.
  2. &value returns address of type int*
  3. 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

Related Questions