user7982333
user7982333

Reputation:

Implicit conversions and pointers?

Why does an implicit conversion not happen when making a float pointer point to an integer, such as when you assign a float variable an integer value?

Upvotes: 0

Views: 870

Answers (2)

I think it's easy to reason about it via allegory.

Think of a pointer as slip of paper with the address of a house written on it. The type of the data is the name of the person who resides in said house.

Now, casting a pointer is like taking that slip of paper, keeping the address the same (for the most part), but changing the name of the person who supposedly lives in the house.

Just because we changed the name on the paper from Alice to Bob, doesn't mean Alice magically becomes Bob. The paper doesn't influence the house.

That's why using such a pointer has undefined behavior. The code think it's addressing a Bob, when in fact it's Alice.

Upvotes: 2

Sam Varshavchik
Sam Varshavchik

Reputation: 118292

Because a pointer, well, it needs to point someplace. Because that's what a pointer is. When you have an

int *p;

And you dereference it, like, for example:

foo(*p);

You expect to dereference the pointer and end up with an int.

Now, if you start with a float:

float *q;

And let's say, for the sake of argument, you can do this:

int *p=q;

Then where exactly do you expect this pointer to point to, now? It can't point to wherever q is pointing to. Because the only thing over there is a float.

So, you have to do it yourself, manually:

int n= (int)*q;
int *p= &n;

And, of course, you have to make sure that n remains in scope as long as the p pointer gets dereferenced. And, if *q is changed to a different value, it won't affect what p is pointing to. But those would be different questions...

Upvotes: 1

Related Questions