Should I disable the C compiler signed/unsigned mi

2020-07-03 03:56发布

The Microsoft C compiler warns when you try to compare two variables, and one is signed, and the other is unsigned. For example:

int a;    
unsigned b;

if ( a < b ) { // warning C4018: '&lt;' : signed/unsigned mismatch

}

Has this warning, in the history of the world, ever caught a real bug? Why's it there, anyway?

11条回答
Lonely孤独者°
2楼-- · 2020-07-03 04:28

@gimel The explanation about shoot the entire leg of found behind your link is really good for this problem.

-"Someone who avoids the simple problems may simply be heading for a not-so-simple one."

This is actually always true when you convert between different types and you don't check for those values that could hurt you.

/Johan

Update: The correct way to convert from uint to int is to check the values against limits.h, or something like that. (But I seldom do that my self, even thou I know I should... :-)

查看更多
我命由我不由天
3楼-- · 2020-07-03 04:29

I've been writing code longer than I'd care to admit. From personal experience ignoring seemingly pedantic compiler warnings can sometimes yield very unpleasent results.

If they annoy you and you accept/understand the situation then set a cast and move on.

Eventually these things move from an overlooked nuance into a conscious decision when designing new code. The result leaves less room for mickmouse corner cases to ruin your or your customers day and overall better quality software.

查看更多
萌系小妹纸
4楼-- · 2020-07-03 04:35

I think its best to convert your UNsigned number into a signed number (before the comparison). Rather than the other way around.

查看更多
够拽才男人
5楼-- · 2020-07-03 04:36

Never ignore compiler warnings.

查看更多
别忘想泡老子
6楼-- · 2020-07-03 04:43

You should change a and b to both use signed types, or both use unsigned types. But that may not be practical (e.g. it maybe outside your control).

The warning is there to catch comparisons between a signed integer with a negative value and an unsigned integer -- if the magnitudes of both numbers are small, the former will (incorrectly) be deemed larger than the latter.

查看更多
在下西门庆
7楼-- · 2020-07-03 04:44

Just one of the many ways in which C allows you to shoot yourself in the foot - you'd better know what you are doing. The C quote is attributed to Bjarne Stroustrup, creator of C++.

查看更多
登录 后发表回答