I have defined a custom assert macro. This works fine for all other comparisons. However, I get the compiler error:
ISO C++ forbids comparison between pointer and integer
when using the macro shown below (DWASSERT) to compare pointers as in the code below.
#define DWASSERT(condition,printstatement) if(!condition){ printf(printstatement); assert(condition); }
#include <stdio.h>
int main()
{
int target = 0;
int* ptr1 = ⌖
int* ptr2 = ⌖
//Normal comparison works fine
if(ptr1 == ptr2)
printf("Equal");
//Comparison using Macro generates compiler
//error on the next line
DWASSERT(ptr1 == ptr2, "Pointers not equal!\n");
return 0;
}
While I can simply avoid using DWASSERT for this case, I am curious as to why this compiler error is generated.
The problem is that
DWASSERT(ptr1 == ptr2, ...gets expanded toif(!ptr1 == ptr2){ printf(...Do you see what’s going on?
!ptr1 == ptr2is equivalent to(!ptr1) == (ptr2), and since!ptr1is an integer type andptr2is a pointer type, you get your error.What you need to do to fix this is to change your macro definition to:
Also, keep in mind that it is a bad idea to use
printfthe way you have, with an arbitrary string as a format. At some point somebody will give you a string with a%in it and things will break. You should use something likeputs(x)orprintf("%s", x).