Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing two different types of pointer

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?

like image 353
msc Avatar asked Oct 20 '25 22:10

msc


1 Answers

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.

like image 81
AnT Avatar answered Oct 23 '25 13:10

AnT