Why does using long as datatype make 'implicit conversion loses integer precision' disappear?

  • A+
Category:Languages

I know there are lots of questions with this title but i am not looking for a solution. I would like to know why this works. I have this given as a solution

int points[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  int *pos = points + 5;  int index = pos - points; 

but when i use that code i get the warning implicit conversion loses integer precision:'long' to 'int'. Now when i use long instead as datatype of index

int points[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  int *pos = points + 5;  long index = pos - points; 

it gives no warning. I tried to use long because i remembered something about pointers and long. But Pointers do not have a datatype(if i am wrong please correct me). Both points and *pos are initialized with int. So why does long fit and int does not?

Why do they use int in the solution? Is the solution wrong or is it about xCode(which i am working with)?

Thank you for answering


but when i use that code i get the warning implicit conversion loses integer precision:'long' to 'int'.

This means that on your platform, the difference of two pointers is of type long.

I tried to use long because i remembered something about pointers and long. But Pointers do not have a datatype(if i am wrong please correct me).

You're wrong, everything has a type in C. Pointers have pointer types. The difference between two pointers is a signed integer type, but the standard doesn't specify which one, different platforms will use different types.

But the standard specifies a typedef by the name ptrdiff_t (defined in stddef.h) which must be defined to the signed integer type of a pointer difference, so this is the type you should use for the kind of code you show.

Both points and *pos are initialized with int. So why does long fit and int does not?

The type pointers point to is something different than the pointers themselves. Pointers are addresses, and on your system, addresses can be larger than int values.

Why do they use int in the solution? Is the solution wrong

Yes, it's wrong. As explained above, the expression pos - points is some signed integer type, and it might be an int on some platforms, but you can't assume that.

Of course, the following would be ok as well:

int points[10] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 };  int *pos = points + 5;  int index = (int)(pos - points); 

In this example, you know the result can be represented in an int, so you can just convert it by an explicit cast. But don't do that in general.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: