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
- Use an unsigned/size_t index when comparing against .size().
- 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
gcc/clang "narrowing conversion inside { }" in CIFix gcc/clang "narrowing conversion of X inside { }" in CI - brace initialization forbids implicit narrowing…
gcc/clang "'X' does not name a type" (missing include) in CIFix gcc/clang "'X' does not name a type" in CI - a type is used before it is declared, usually a missing incl…
gcc/clang "cannot find -lX" during compile-link in CIFix gcc/clang "cannot find -lX" during a one-step compile-and-link in CI - the named library is not installed…