C4018
Visual C++ Programming Language
Severity: MinorWhat Does This Error Mean?
C4018 is a warning that you compared a signed integer with an unsigned integer. The comparison produces unexpected results when the signed value is negative: a value of -1 compared to an unsigned size_t becomes a very large positive number on most platforms, making -1 appear greater than any positive value. The fix is to cast the signed value to unsigned, or use a signed type for the counter.
Affected Models
- Visual Studio 2015–2022
- MSVC v14.x / v17.x
Common Causes
- Comparing an int loop counter with vector.size() or string.length(), which return size_t (unsigned)
- Comparing a function return value of int with a container size
- Mixing int and DWORD (unsigned 32-bit) in Windows API comparisons
- Using ptrdiff_t (signed) against size_t (unsigned) arithmetic
How to Fix It
-
Change the loop counter type to match the unsigned type. Use size_t i = 0 instead of int i = 0 when comparing with container sizes.
size_t is the correct type for container indices and sizes on all platforms. Using size_t eliminates C4018 and is also correct on 64-bit systems where containers can exceed 2 billion elements.
-
Cast the unsigned value to a signed type if you need a signed counter. Use static_cast<int>(vec.size()) to convert the size before comparison.
Only safe when you are certain the value fits in int (i.e. the container has fewer than 2 billion elements). For very large containers, use size_t throughout.
-
In C++11 and later, use a range-based for loop to iterate containers. This avoids index comparisons entirely and eliminates C4018.
Range-based for loops are cleaner and immune to signed/unsigned comparison bugs. Use them whenever you do not need the index value itself.
Frequently Asked Questions
Will C4018 cause an actual bug?
Yes, in specific cases. If your signed variable is ever negative (an error code, for example) and you compare it with a size_t, the signed negative value wraps to a huge unsigned number and the comparison behaves incorrectly. This class of bug is subtle and hard to debug — treat C4018 as a real warning.