I have a typed pointer, typed
, that was initialized using pointer arithmetic to point to an object within an array. I also have a function that takes two pointer args, the 1st typed the same as the afore-mentioned pointer and the 2nd is void *
(see myfunc()
in the code below).
If I pass typed
as the 1st argument and another pointer typed the same as typed
as the 2nd argument, and then compare these for equality within the function, is that Undefined Behavior?
#include <stdio.h>
typedef struct S {int i; float f;} s;
void myfunc(s * a, void * b)
{
if (a == b) // <-------------------------------- is this UB?
printf("the same\n");
}
int main()
{
s myarray[] = {{7, 7.0}, {3, 3.0}};
s * typed = myarray + 1;
myfunc(typed, &(myarray[0]));
return 0;
}
Update: Ok, so I come back a day after posting my question above and there are two great answers (thanks both to @SouravGhosh and @dbush). One came in earlier than the other by less than a minute (!) but from the looks of the comments on the 1st one, the answer was initially wrong and only corrected after the 2nd answer was posted. Which one do I accept? Is there a protocol for accepting one answer over the other in this case?
This comparison is well defined.
When a
void *
is compared against another pointer type via==
, the other pointer is converted tovoid *
.Also, Section 6.5.9p6 of the C standard says the following regarding pointer comparisons with
==
:There is no mention here of undefined behavior.