# C/C++: warning: comparison of integer expressions of different signedness: 'int' and 'size_t' [-Wsign-compare]

**Code:** `comparison of integers of different signs` · **Category:** C/C++ · **Seen on:** C/C++, GCC, Clang

A signed integer is compared with an unsigned one; the signed value is converted to unsigned, so a negative number becomes huge.

## Meaning

`for (int i = 0; i < v.size(); ++i)` triggers it because `size()` returns an unsigned `size_t`. With -1, the comparison `-1 < 5u` is false. Use `size_t` for indices, range-for, or cast deliberately after checking the sign.

## Common causes

- Looping with `int i` against `container.size()`
- Comparing a possibly negative `int` with `size_t`/`unsigned`
- Mixing `long` and `unsigned long` variables
- Arithmetic that subtracts from `size()` and wraps below zero

## Quick fix

1. Use `size_t` or `auto` for indices
2. Prefer range-based for loops
3. Check `i >= 0` before casting

## Detailed fix by platform

### C++

1. `for (std::size_t i = 0; i < v.size(); ++i)` or `for (const auto& x : v)`
2. C++20: `std::ssize(v)` returns a signed size

## Code examples

### The classic loop

```cpp
#include <vector>
#include <cstddef>

void run(const std::vector<int>& v) {
    // for (int i = 0; i < v.size(); ++i)      // warning: comparison of integer expressions of different signedness
    for (std::size_t i = 0; i < v.size(); ++i) {}
    for (const auto& x : v) { (void)x; }       // best: no index at all
}
```

## How to diagnose

1. **Types** — Which operand is unsigned?
2. **Range** — Can the signed value be negative?
3. **Loop** — Can a range-for replace the index?

---
Source: [WhatIsMyError](https://whatismyerror.com/errors/cpp/signed-unsigned-comparison)
