I don't know why (-1 < s.size()) evaluates to false, when -1 is less than 3.
Code:int main()
{
string s = "abc";
cout << s.size() << '\n';
if (-1 < s.size()) {
cout << "yes";
} else {
cout << "no";
}
keep_window_open();
}
Printable View
I don't know why (-1 < s.size()) evaluates to false, when -1 is less than 3.
Code:int main()
{
string s = "abc";
cout << s.size() << '\n';
if (-1 < s.size()) {
cout << "yes";
} else {
cout << "no";
}
keep_window_open();
}
s.size() returns a string::size_type, which is indirectly a typedef for size_t, which is an unsigned integer type (typically itself a typedef for unsigned int).
So, -1 < s.size() is a comparison between a signed and unsigned integer. The conversion of -1 to an unsigned integer resulted in a number larger than what s.size() returned.
Is there an easy way to fix this?
Yes, just write:Quote:
Is there an easy way to fix this?
Code:int main()
{
string s = "abc";
cout << s.size() << '\n';
cout << "yes";
keep_window_open();
}
laserlight: haha lolo! :D
really strange, one unsigned other signed and they promote the signed to unsigned?
actually i think you would get a warning, which will ask for a cast, and this will fix the problem, before it annoys you.
Yes, it should indeed prompt a warning. When comparing integers, make sure both are of the same type.
I'm using Visual C++ and it didn't warn me. I didn't change any warning levels either.
All Visual Studio versions I've used has warned on signed/unsigned comparison, even on default warning levels. What version are you using?
Microsoft Visual Studio 2008 Version 9.0.21022.8 RTM
In project settings, under C/C++, make sure "Warning level" is set to 4.
In the output window, check for warnings in the output.
If using the Task List, make sure the Warning button isn't deselected (thus silencing the warnings).
You should get warnings about it.
But W4 is the only one that can warn about potentially uninitialized variables and unused variables and the use of non-standard extensions, so I suggest leaving it on W4 (level 4).