How to generate a compilation error with different types of pointers?

How to write a macro CHECK (a, b), which generates a compilation error when two pointers a and b have a different base type.

CHECK((int*)0, (char*)0) -> compilation error
CHECK((int*)0, (int*)0) -> works

I am looking for C89 code, but C99 + gcc extensions will also do.

+2
source share
3 answers

EDIT now works for any type, not just pointers

Something more or less removed from the Linux kernel using the GCC extension typeof().

This generates a warning at compile time, it also works for integer pointer types

#define CHECK(a, b) do { \
    typeof(a) _a; \
    typeof(b) _b; \
    (void) (&_a == &_b); \
    } while (0)

int main(int argc, char **argv)
{
    int *foo;
    int *bar;
    char *baz;

    CHECK(foo, bar);
    CHECK(bar, baz);
    return 0;
}
+4
source

I do not know how to do this using macros. If you can use C ++ then look here

0

You can try as follows:

#define CHECK(A,B) do { typeof(*A) _A; typeof(*B) _B; _A = _B; } while (0)

If your base types, not integer types (char, int, short, long, long long), the types will not advance, so the assignment _A = _Bwill not be performed.

I don't think there is a way to make it work for integer types.

0
source

Source: https://habr.com/ru/post/1659376/


All Articles