mixing unsigned and signed

This is a discussion on mixing unsigned and signed within the C++ Programming forums, part of the General Programming Boards category; One thing that always annoyed me about C and C++ is that sometimes you are forced to mix unsigned and ...

mixing unsigned and signed

One thing that always annoyed me about C and C++ is that sometimes you are forced to mix unsigned and signed types. For instance when you pass an array to a function and to be correct you better pass a size_t as the size too.

Then if you loop through the array with an int you get the warning that you're mixing unsigned and signed types but if you change it to size_t and the SetVal expects an int then you get the warning there.

Then if you loop through the array with an int you get the warning that you're mixing unsigned and signed types but if you change it to size_t and the SetVal expects an int then you get the warning there.

How do you guys solve this?

It really depends. Your code as written needs to do more error checking that it does, or have a documented set of preconditions (eg n <= 3) that is enforced by the caller.

The only catch is that it's not possible to define variables of two distinct types within the for() construct, which is the reason I've moved the variable definitions before the loop. There is potentially a (very slight) overhead in this but, if the relationship between i and i_as_int is well defined (eg above: they're equal value, although different types) modern compilers will often optimise out one of the variables anyway.

In C++, one other way is to overload the SetVal() member function so it accepts either int or a size_t. Of course, that forces one of the SetVal() functions to do a conversion, but at least it's localised.

Don't implicit casts between signed and unsigned happen all the time and you can do very little about it? Isn't the compiler more worried about the comparison of different types (even though here you know that there is no reason to be worried)?

Another option might be to modify SetVal to accept size_t too (and change the type of the underlying variable) if, as it appears from this usage, you will only be setting it to positive values anyway.

Basically, you can do complicated things like grumpy shows or cast everything, but the behavior of the program won't change a bit whether you just let compiler do implicit cast, cast explicitly or use more variables to "avoid casting" - if there's an overflow it will happen the same no matter what you do. (To be safe, wouldn't you need to check before any operation whether it will overflow, something which you won't need to do if the ranges are well known?) So the only objective might be to silence the compiler warnings (which is safe here since you know the limits of possible values)?