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(); }
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.
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
Is there an easy way to fix this?
Yes, just write:Is there an easy way to fix this?
Code:int main() { string s = "abc"; cout << s.size() << '\n'; cout << "yes"; keep_window_open(); }
Look up a C++ Reference and learn How To Ask Questions The Smart WayOriginally Posted by Bjarne Stroustrup (2000-10-14)
laserlight: haha lolo!
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.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.
I'm using Visual C++ and it didn't warn me. I didn't change any warning levels either.
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.
Compilers can produce warnings - make the compiler programmers happy: Use them!
Please don't PM me for help - and no, I don't do help over instant messengers.