Skip to content
Latchkey

gcc/clang "comparison between signed and unsigned" (-Werror) in CI

Comparing a signed and an unsigned integer converts the signed value to unsigned, which can flip the result for negatives. Under -Werror=sign-compare this warning becomes a build failure.

What this error means

A loop comparing an int index against a .size() (which is unsigned) fails with "comparison of integer expressions of different signedness", only with -Werror.

gcc
app.cpp:6:19: error: comparison of integer expressions of different signedness:
'int' and 'std::vector<int>::size_type' {aka 'long unsigned int'} [-Werror=sign-compare]
    6 |   for (int i = 0; i < v.size(); ++i)
      |                   ~~^~~~~~~~~~

Common causes

How to fix it

Match the signedness

  1. Use an unsigned/size_t index when comparing against .size().
  2. Or cast one operand so both sides share a type.
gcc
for (std::size_t i = 0; i < v.size(); ++i) { /* ... */ }

How to prevent it

  • Index containers with size_t (or use range-based for) so loop bounds and container sizes share signedness.

Frequently asked questions

What causes ""comparison between signed and unsigned""?
A loop comparing an int index against a .size() (which is unsigned) fails with "comparison of integer expressions of different signedness", only with -Werror.
How do I fix "comparison between signed and unsigned"?
Match the signedness

Related guides

References

Latchkey auto-heals failures like this one - detected, fixed, and retried without you. Start free → 30-day trial · No credit card