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条回答
做自己的国王
2楼-- · 2020-07-03 04:47

The warnings are there for a purpose... They cause you to think hard about your code!

Personally, I would always explicitly cast the signed --> unsigned and unsigned --> signed if possible. By doing this you are ensuring that you take ownership of the transaction and that you know whats going to happen. I realise that it might not always be possible, depending on the project to do this, but always aim for 0 compiler warnings ... it can only help!

查看更多
▲ chillily
3楼-- · 2020-07-03 04:50

Oh it has. But the other way around. Ignoring that warning caused a huge headache to me one day. I was writing a function that plotted a graph, and mixed signed and unsigned variables. In one place, i compared a negative number to a unsigned one:

int32_t t; ...
uint32_t ut; ...

if(t < ut) { 
    ...
}

Guess what happened? The signed number got promoted to the unsigned type, and thus was greater at the end, even though it was below 0 originally. It took me a couple of hours until i found the bug.

查看更多
Luminary・发光体
4楼-- · 2020-07-03 04:50

binary operators often convert both types to the same before doing the comparison, since one is unsigned, it will also convert the int to unsigned. Normally this won't cause too much trouble but if your int is a negative number, this will cause errors in comparisons.

e.g. -1 is equal to 4294967295 when converted from signed to unsigned, now compare that with 100 (unsigned)

查看更多
手持菜刀,她持情操
5楼-- · 2020-07-03 04:55

If you have to ask the question, you do not know enough about whether it is safe to disable it, so the answer is No.

I wouldn't disable it - I don't assume I always know better than the compiler (not least because I often don't), and more particularly because I sometimes make mistakes by oversight when a compiler does not.

查看更多
Juvenile、少年°
6楼-- · 2020-07-03 04:55

I have even configured the compiler to make that warning an compile error. for the reasons all the other guys already mentioned.

If I ever encounter a signed/unsigned mismatch I ask myself why I chose different "signedness". It usually is a design error.

查看更多
登录 后发表回答