Warning C4018

Hello,

In nearly all my coding projects which, due to their nature, are 90% for loops of the form
 
for (int i = 0; i < somelist.size(); ++i) { .. }

I ultimately get my build logs cramped up with warning c4018 (" signed/unsigned mismatch"). I realize this is because .size() can only be a positive integer.

The loop itself is basic enough and due to its form it can't actually go wrong. However, since it shows warnings, I can't help but wondering whether I'm doing something wrong. Thus, my question is: is there a way to avoid this? I know using 'unsigned int i' fixes it, but typing the entire 'unsigned' word each time seems stupid. Similarly, I can first use "int imax = somelist.size()" and then use imax as the upper limit, but making such a redundant variable seems silly. So, is there a good way to avoid this?

(P.S.: I don't want to turn off/down the warning level. I still make quite a lot of mistakes thus the warnings often come in handy. I'm just annoyed that the large list of C4018 warnings makes it difficult to find "real" warnings.)
I dont know the type is returned by the function size().. I guess its return unsigned integer

Its simple and very much possible that is why you are receiving the warning.

Well just change the variable type of i, change to unsigned integer
@johny10151981: He said that he thought of doing that...

By what you've said, it sounds like the best option is a typedef which is already done for you in some (if not all) compilers.
How do you mean? You mean simply typedef'ing a shorter name for "unsigned int" and use that as loop index variable type?
Is somelist actually a std::list<> container?
If so maybe you should use its own size_type.
It's not necessarily a list, but usually one of the std containers, so I'll be testing size_type. Thanks for the tip.

I wonder though: what's the point of size_type (and, in the same area, size_t)? What else could a size be than an unsigned integer?
Topic archived. No new replies allowed.