3

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?

einpoklum
  • 118,144
  • 57
  • 340
  • 684
jureslak
  • 195
  • 2
  • 9
  • 1
    Sounds like a bug. `gcc` normally implements this warning, as shown in https://stackoverflow.com/questions/3598556/g-warning-comparison-of-unsigned-expression-0-is-always-false – Barmar Nov 09 '17 at 17:18
  • 4
    gcc [normally catches these types of issues using -Wconversion](https://stackoverflow.com/a/22047204/1708801) but it looks like it breaks for templates ... seems like a bug, please [file a bug](https://gcc.gnu.org/bugzilla/) – Shafik Yaghmour Nov 09 '17 at 17:22
  • Yeah, it works on simpler examples, I just wanted to check if there is some trick involving templates, before filing a stupid bug report. Thanks! – jureslak Nov 09 '17 at 17:30
  • 3
    Filed as [bug82924](https://gcc.gnu.org/bugzilla/show_bug.cgi?id=82924). – jureslak Nov 09 '17 at 20:08

1 Answers1

1

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).

einpoklum
  • 118,144
  • 57
  • 340
  • 684