Home > Blockchain >  C4389 signed/unsigned mismatch only for x86 compilation c
C4389 signed/unsigned mismatch only for x86 compilation c

Time:06-03

I am seeing a C4389: "'==': signed/unsigned mismatch" compiler warning when I execute the following code in Visual Studio using the x86 compiler using a warning level of 4.

#include <algorithm>
#include <vector>

void functionA()
{
    std::vector<int> x(10);

    for(size_t i = 0; i < x.size(); i  )
    {
        if (std::find(x.begin(), x.end(), i) != x.end())
        continue;
    }
}

Can someone explain to me why this happens and how I can resolve this?

Here is a link https://godbolt.org/z/81v3d5asP to the online compiler where you can observe this problem.

CodePudding user response:

You have declared x as a vector of int – but the value you are looking for in the call to std::find (the i variable) is a size_t. That is an unsigned type, hence the warning.

One way to fix this is to cast i to an int in the call:

if (std::find(x.begin(), x.end(), static_cast<int>(i)) != x.end())

Another option (depending on your use case) would be to declare x as a vector of an unsigned integer type:

std::vector<unsigned int> x(10);
  • Related