Sign in to follow this  
janta

[c++] compiler warning when unsigned used in "less than 0" comparison?

Recommended Posts

Anyone knows if some compiler have such a warning? Do you see any reason they shouldn't? In my experience it could be usefull to catch some stupid mistakes. The most famous probably being iterating backwards on an array like for "(uint i = size - 1; i < 0 ; i--)", though being bitten by this tends to be immediately noticeable, but in other situations it can be more subtle What do you think?

Share this post


Link to post
Share on other sites
I assume you mean for(unsigned int i = size - 1; i >= 0; i--).

I'm not sure how useful it would be in general, since this is only one very specific case of integer overflow. You do get a warning if you have unsigned int and int on either side of the comparison (i.e. int a = 0; for(unsigned int i = size - 1; i >= a; i--) will give you a warning).

Much more subtle examples of integer overflow would be things like if (a + 100 > c) and there's just no way you can expect the compiler to warn you about that. Even more subtle is this one

Share this post


Link to post
Share on other sites
That's my point Pallidine, I never came across a situation where a programmer actually writes (u < 0) as an intentionally always true condition. In my experience it's always a mistake that leads to unintended behavior, hence I think a warning would be nice,

Quote:
Original post by Codeka
I assume you mean for(unsigned int i = size - 1; i >= 0; i--).

Yes sorry :)

Share this post


Link to post
Share on other sites
gcc indeed has such a warning. Invoke with -Wall, and it will tell you about most of your shady practices like this. How to get equivalent effects with other compilers, I can't tell you.

Share this post


Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this