Hi, I am running a very small program and I am getting the warning "comparison between signed and unsigned integer expressions". Everything I read just says you should assign the value to an unsigned, but doesnt actually explain why, and I do not understand.
If someone could explain this, I would help greatly. Thank you
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int wordCount(string input);
int main()
{
string input;
input = "The quick brown fox jumps over the lazy dog";
wordCount(input);
}
int wordCount(string input)
{
int spaces = 0;
for ( int i = 0; i < input.length(); i++)
{
if (input.substr(i,1) == " " )
{
spaces++;
}
}
cout << spaces;
}
// Example program
#include <iostream>
#include <string>
usingnamespace std;
int wordCount(string input);
int main()
{
string input;
input = "The quick brown fox jumps over the lazy dog";
wordCount(input);
}
int wordCount(string input)
{
int spaces = 0;
for (unsignedint i = 0; i < input.length(); i++)
{
if (input.substr(i,1) == " " )
{
spaces++;
}
}
cout << spaces;
}
The reason for the warning is that the result could surprise:
1 2 3 4 5 6 7 8 9 10 11
#include <iostream>
int main()
{
int x = -1;
size_t y = 1;
if ( x < y ) // warning: .. [-Wsign-compare]
std::cout << "yes\n";
else
std::cout << "no\n";
}
The position and length of string are unsigned, because (a) negative values would not be logical and (b) unsigned ints can index longer arrays than signed.
You should not cout anything in your wordCount(). Just compute and return an answer. That way the function is more reusable. Let the caller decide what they do with the number.
C++20 introduces std::ssize to easily give a signed version of the container size. https://en.cppreference.com/w/cpp/iterator/size
...but C++20 isn't actually released yet so you'll have to wait a bit. For now, just make i be size_t, or cast the .size() call to a [signed] int to avoid the warning.