0

I wrote the following lines of code:

int pos = 0, last_pos = 0;
while ((pos = str.find_first_of(" ", last_pos)) != string::npos)

But the compiler is showing an error:

error: comparison between signed and unsigned integer expressions [-Werror=sign-compare]
     while ((pos = str.find_first_of(" ", last_pos)) != string::npos)
                                                                            ^

How may I fix that? It's the first time I see this

  • 1
    Your `pos` should be `size_t`, which is unsigned – Vlad Feinstein Aug 05 '20 at 23:48
  • 2
    `string::npos` return type is `std::size_t` which is what you should use for the type of your variable `pos`. Read [this](https://stackoverflow.com/questions/859943/how-can-i-fix-warnings-like-comparison-between-signed-and-unsigned) for how to deal with this warning. – stateMachine Aug 05 '20 at 23:51
  • 2
    Your `pos` should be `std::string::size_type`, which is unsigned. Both the `find` method and the `std::string::npos` are unsigned quantities. – Thomas Matthews Aug 06 '20 at 00:17

1 Answers1

5

Looks like someone cranked up the warning level on your tools and turned the warnings into hard, compilation-halting errors. This is a good thing most of the time and especially while learning because you can no longer ignore the compiler warnings1.

The position and size information returned by string methods are all unsigned. After all, what use would a string of negative length be? If you look at documentation for find_first_of you'll see it doesn't return int; it returns size_type. With a little more poking around you'll find size_type is an unsigned integer of one type or another defined by your development tool's library implementation. If you go digging through the Standard Library's implementation headers, you'll find the actual type represented by size_type, but you don't need to know the exact type. Just use size_type and let the compiler figure out the details.

So...

int pos = 0, last_pos = 0;
while ((pos = right_token.find_first_of(" ", last_pos)) != string::npos)

should be

string::size_type pos = 0, last_pos = 0;
while ((pos = right_token.find_first_of(" ", last_pos)) != string::npos)

1 Compiler errors are invalid syntax, bad grammar, that make it impossible for your source code to be translated into executable code. Compiler warnings are syntactically correct code, but the compiler is concerned there may be questionable logic and the program will not behave as you expect. Often it's right, and investigating the warning will save you time debugging an error at runtime. But sometimes it's warning about something you aren't likely to encounter. In this particular case you need to need to have a HUGE string, likely gigabytes long, for the logic error to manifest.

user4581301
  • 33,082
  • 7
  • 33
  • 54