[cfe-dev] Possibly invalid enum tautology warning

Peter Geoghegan peter at 2ndquadrant.com
Sun Aug 7 06:44:13 PDT 2011


Consider the attached testcase. When built with Clang from SVN tip, it
produces the following warning:

clang_testcase.c:21:11: warning: comparison of unsigned enum expression < 0 is
      always false [-Wtautological-compare]
        if (test < 0)
            ~~~~ ^ ~

Clang has made the enum in the testcase unsigned. This is perfectly
reasonable - the C standard gives leeway as to how the enum can be
represented, so both GCC and Clang will make the representation
unsigned unless they're forced to make it signed by the fact that the
definition explicitly sets constants to negative integer values.

What's also true is that compilers may opt to invariably make enums
signed. While I'm not aware that any compiler does so, I'm also not
aware that they all don't, and I sincerely doubt that the optimisation
GCC and Clang perform here to maximize the number of values that can
be represented is all that useful in practice, so I can certainly
imagine compiler vendors not bothering with it.

Anyway, the above test could be perfectly valid in the case where some
compiler's enum representation is signed. That isn't true of Clang or
GCC, but I feel that Clang should aim to both follow the standard to
the letter and follow it in spirit, allowing people to write portable
code. If you find this scenario implausible, consider that this
actually happened on Postgres, due to the fact that we checked that a
certain enum variable's value could be safely used as an array
subscript within our client library, libpq. We weren't about to trust
arbitrary client code to not pass an invalid value.

I am aware that using the constant literal in place of 0 prevents the
warning from being seen. Nonetheless, I thought that it was worth
considering if this is a case that we could handle better.

Incidentally, Clang now builds Postgres without any warnings, other
than a warning that we get with GCC too and can't really do anything
about. I've blogged about it. Impressively, Clang caught a bug that,
if a certain struct had been used a certain way that we'd generally
consider to be perfectly reasonable, would have resulted in undefined
behaviour. Luckily or unluckily, it actually wasn't being used that
way, but that could have easily changed over time.

-- 
Peter Geoghegan       http://www.2ndQuadrant.com/
PostgreSQL Development, 24x7 Support, Training and Services
-------------- next part --------------
A non-text attachment was scrubbed...
Name: clang_testcase.c
Type: text/x-csrc
Size: 320 bytes
Desc: not available
URL: <http://lists.llvm.org/pipermail/cfe-dev/attachments/20110807/bd67e703/attachment.c>


More information about the cfe-dev mailing list