In C programming, comparing two different types of pointers like this :
int i = 1;
double d = 2.5;
int *ip = &i;
double *dp = &d;
if(ip != dp) // is it UB?
printf("Not same\n");
Is ip != dp undefined behaviour in C?
In C programming, comparing two different types of pointers like this :
int i = 1;
double d = 2.5;
int *ip = &i;
double *dp = &d;
if(ip != dp) // is it UB?
printf("Not same\n");
Is ip != dp undefined behaviour in C?
The direct comparison ip != dp is invalid in C. Specification of != operator does not allow mixing int * and double * pointers in one comparison. It is a constraint violation in C (aka a "compile error"). A conforming C compiler will report your code as invalid by issuing a diagnostic message.
What happens next depends solely on your compiler. It has nothing to do with C language.
Referring to this code as "C code that produces undefined behavior" would be misleading. It is formally true, but it makes exactly as much sense as saying that the text of "War and Piece" is "C code that produces undefined behavior" (in some strange C compiler that accepts it).
The key point here is that this code language constraints meaning that it is not C code at all.
This is not well defined. A prerequisite of the != operator is that if both operands are pointers, they must be to compatible types. int and double are not compatible types.
From section 6.5.9 of the C standard:
2 One of the following shall hold:
— both operands have arithmetic type;
— both operands are pointers to qualified or unqualified versions of compatible types;
— one operand is a pointer to an object type and the other is a pointer to a qualified or unqualified version of void; or
— one operand is a pointer and the other is a null pointer constant.
Yes this operation is undefined, and Kernighan & Ritchie were mentioned about that in their book "The C Programming Language":
Any pointer can be meaningfully compared for equality or inequality with zero. But the behavior is undefined for arithmetic or comparisons with pointers that do not point to members of the same array.
This means that pointers that points to different types cannot be checked for equality.