Search code examples
cpointerscastingimplicit-conversion

Why is an error is generated when I type cast a pointer and subtract it?


Why doesn't typecasting work here..?

#include<stdio.h>
int main(){
   int x = 5;
   float y = 7.0;
   float *p = &y;
   int *q = &x;
   printf("p is %d\nq is %d\np - q is %d", p, q, (p - q));
   return 0;  
  }

I am getting this error

invalid operands of types 'float*' and 'int*' to binary 'operator-'

what does it mean?


Solution

  • The error means that the compiler is unable to deduce the common type of two operands one of which has the type float * and other int *. There is no implicit conversion between these types.

    But in any case the program has undefined behavior because at least you may not subtract two pointers that do not point to elements of the same array or to a memory after the last element of the same array.

    From the C Standard (6.5.6 Additive operators)

    9 When two pointers are subtracted, both shall point to elements of the same array object, or one past the last element of the array object; the result is the difference of the subscripts of the two array elements.

    And using incorrect conversion specifiers (as for example %d with a pointer) for supplied arguments in the function printf also invokes undefined behavior.

    From the C Standard (7.21.6.1 The fprintf function)

    9 If a conversion specification is invalid, the behavior is undefined.275) If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.