C++核心準(zhǔn)則ES.100:不要混用有符號數(shù)和無符號數(shù)

ES.100: Don't mix signed and unsigned arithmetic
ES.100:不要混用有符號數(shù)和無符號數(shù)
Reason(原因)
Avoid wrong results.
避免錯(cuò)誤的結(jié)果。
Example(示例)
int x = -3;
unsigned int y = 7;
cout << x - y << '\n'; // unsigned result, possibly 4294967286
cout << x + y << '\n'; // unsigned result: 4
cout << x * y << '\n'; // unsigned result, possibly 4294967275
It is harder to spot the problem in more realistic examples.
在更加貼近實(shí)際開發(fā)的代碼中發(fā)現(xiàn)問題會(huì)更加困難。
Note(注意)
Unfortunately, C++ uses signed integers for array subscripts and the standard library uses unsigned integers for container subscripts. This precludes consistency. Use?gsl::index?for subscripts;?see ES.107.
不幸的是,C++使用有符號整數(shù)作為數(shù)組的下標(biāo),而標(biāo)注庫使用無符號整數(shù)作為數(shù)組的小標(biāo),這破壞了一致性原則。使用gsl::index作為下標(biāo)。參見ES.107。
Enforcement(實(shí)施建議)
Compilers already know and sometimes warn.
編譯器可以識別這方面的問題,有時(shí)會(huì)發(fā)出警告。
(To avoid noise) Do not flag on a mixed signed/unsigned comparison where one of the arguments is?sizeof?or a call to container?.size()?and the other is?ptrdiff_t.
(為了避免誤判)當(dāng)一個(gè)參數(shù)是sizeof或者container.size()的返回值,而另一個(gè)參數(shù)是ptrdiff_t的時(shí)候,不要標(biāo)記有符號數(shù)/無符號數(shù)混合的比較操作。
原文鏈接
https://github.com/isocpp/CppCoreGuidelines/blob/master/CppCoreGuidelines.md#es87-dont-add-redundant--or--to-conditions
覺得本文有幫助?請分享給更多人。
關(guān)注微信公眾號【面向?qū)ο笏伎肌枯p松學(xué)習(xí)每一天!
面向?qū)ο箝_發(fā),面向?qū)ο笏伎迹?/span>
