osa1 github gitlab twitter cv rss

Implicit casts

May 25, 2013 - Tagged as: en, cpp, types.

I wrote a C++ code like this:

int max_number_of_something = -1;
set<some_type> s;


if (s.size() > max_number_of_something)
    max_number_of_something = s.size();

The problem with this code is that this conditional will never be taken, and no errors will be raised either. This is because type of s.size() is unsigned and in the expression s.size() > max_number_of_something, max_number_of_something will be casted to unsigned, implicitly. So -1 is now 4294967295 and no other 32bit unsigned integer is bigger than that number.

Another reason to not to like weak typing and implicit type casts.