Search code examples
cpointersgcccompiler-warningsgcc-warning

gcc/g++ warning if comparing two pointers' addresses instead of contents?


Suppose I have a function with pointer inputs

void f(int *a, int *b) {
    if (*a < *b) {
        printf("hello!\n");
    }
}

where *a < *b is the correct behavior.

Is there a warning in gcc that I can turn on so whenever I write code such as

a < b

when a, b are int * the compiler would warn me?


Solution

  • There cannot be such warnings, because a < b where both a and b are pointers to int is a legitimate test that your code could do elsewhere.

    A typical use case might be to represent a set of pointers by a sorted vector of pointers searched by dichotomy.

    You might consider customizing GCC with MELT by e.g. adding a #pragma to enable such a warning (in some selected places) but you'll need some time to implement the warning itself. I'm not sure it is worth spending a week of your time to customize GCC this way.

    Technically, the C standard wants a and b to point inside the same aggregate (otherwise it is undefined behavior, or at least unspecified one), but on most systems you can compare any pointers of the same type.