4
votes

I am just getting started in C++.

I am trying to get the first three characters of the string 'str', and compare it to a known string, say, 'knownString'.

To do that, I wrote this line of code:

if (str.substr(start, 3) == knownString)

where 'start' is an integer I declared before. But I keep getting this warning message:

warning: implicit conversion changes signedness: 'int' to 'std::__cxx11::basic_string,** **std::allocator >::size_type' (aka 'unsigned int')

Does anyone knows what I can add or I missed in this statement to fix this?

2
Notice that your original little tweaks to the code actually masked the error. That's what presenting a minimal reproducible example from the start avoids. - Lightness Races in Orbit
Hi Justina. You can make the strategic decision to ignore these warnings in projects where it doesn't matter. If your string will always be below 2GB then you should be fine to just ignore it. The correct way to handle this is to use an explicit conversion, for instance you could do (unsigned int)start instead. Then there's no implicit conversion. - hoodaticus

2 Answers

7
votes

You can:

Either 1. make the conversion explicit:

str.substr(static_cast<std::string::size_type>(start), 3)

Or 2. not make a conversion in the first place:

std::string::size_type start;

Or 3. ask compiler to not warn about it:

g++ compilation arguments -Wno-sign-conversion

I recommend option 2.

6
votes

This warning is triggered by the -Wsign-conversion switch, detecting that you're taking a signed variable and converting it to an unsigned variable, in a way that may change the value.

It doesn't do it for positive literals, where the conversion obviously doesn't change the value, because that would be pointless and really annoying. You'll get it for a negative literal like -5.

(Technically, this is the literal 5 with the unary negation operator applied, not a "negative literal"!).

For named variables it can't really predict what the value would be, so errs on the side of caution.

You should make your variable start have type size_t.