龙空技术网

C++核心准则ES.100:不要混用有符号数和无符号数

面向对象思考 73

前言:

如今咱们对“无符号整数是几位”大体比较关切,大家都想要分析一些“无符号整数是几位”的相关知识。那么小编同时在网摘上收集了一些关于“无符号整数是几位””的相关资讯,希望咱们能喜欢,大家快快来了解一下吧!

ES.100: Don't mix signed and unsigned arithmetic

ES.100:不要混用有符号数和无符号数

Reason(原因)

Avoid wrong results.

避免错误的结果。

Example(示例)

int x = -3;unsigned int y = 7;cout << x - y << '\n';  // unsigned result, possibly 4294967286cout << x + y << '\n';  // unsigned result: 4cout << x * y << '\n';  // unsigned result, possibly 4294967275

It is harder to spot the problem in more realistic examples.

在更加贴近实际开发的代码中发现问题会更加困难。

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++使用有符号整数作为数组的下标,而标注库使用无符号整数作为数组的小标,这破坏了一致性原则。使用gsl::index作为下标。参见ES.107。

Enforcement(实施建议)

Compilers already know and sometimes warn.编译器可以识别这方面的问题,有时会发出警告。(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.(为了避免误判)当一个参数是sizeof或者container.size()的返回值,而另一个参数是ptrdiff_t的时候,不要标记有符号数/无符号数混合的比较操作。

原文链接

觉得本文有帮助?请分享给更多人。

关注微信公众号【面向对象思考】轻松学习每一天!

面向对象开发,面向对象思考!

标签: #无符号整数是几位