jureslak
jureslak

Reputation: 194

gcc gives no warning for comparing unsigned integer < 0 even with Wextra enabled

Take the following code

#include <iostream>

template<typename T>
T f(T x, unsigned y) {
    if (y < 0) return x;
    return static_cast<T>(0);
}

using namespace std;

int main() {

    int a = f(2, 3);
    std::cout << a << std::endl;

    return 0;
}

where function f clearly always returns 0. Compiling it with g++-7.2.0 -Wall -Wextra gives no hint about pointless comparison. However, clang warns us nicely:

a.cpp:7:11: warning: comparison of unsigned expression < 0 is always false [-Wtautological-compare]
    if (y < 0) return x;
        ~ ^ ~
1 warning generated.

Why is this so (I presume templates are the root of the problem) and can gcc be forced to output the warning in this case?

Upvotes: 3

Views: 482

Answers (1)

einpoklum
einpoklum

Reputation: 132096

This is a regression bug in some versions of GCC (including 8.x and 9.x - which are still the default compilers on many distributions at the time of writing).

The bug was tracked here (@jureslak file it again, but that was marked as dupe) and has been resolved. See the warning with GCC 10.1 (Godbolt).

Upvotes: 1

Related Questions