如何处理“签名/未签名的不匹配”警告(C4018)? [英] How do I deal with "signed/unsigned mismatch" warnings (C4018)?

查看:322
本文介绍了如何处理“签名/未签名的不匹配”警告(C4018)?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用C ++编写的大量计算代码,具有高性能和低内存开销。它使用STL容器(大多数向量),并且在每个单个函数中迭代该容器。

I work with a lot of calculation code written in C++ with high performance and low memory overhead in mind. It uses STL containers (mostly vector) a lot, and iterates over that containers almost in every single function.

迭代代码如下所示:

for (int i = 0; i < things.size(); ++i)
{
    // ...
}

它会产生已签名/未签名的不匹配警告(Visual Studio中的C4018)。

but it produces the signed/unsigned mismatch warning (C4018 in Visual Studio).

替换 int 有一些 unsigned 类型是一个问题,因为我们经常使用OpenMP pragmas,它需要计数器 int

Replacing int with some unsigned type is a problem because we frequently use OpenMP pragmas, and it requires the counter to be int.

我要禁止(数百)个警告,但恐怕我错过了一些优雅的解决方案。

I'm about to suppress the (hundreds of) warnings, but I'm afraid I've missed some elegant solution to the problem.

在迭代器上。我认为迭代器是伟大的,当应用在适当的地方。我正在使用的代码将永远不会将随机访问容器更改为 list 或某事(因此使用 int i 已经是容器不可知的),并且始终需要当前索引。你需要输入的所有附加代码(迭代器本身和索引)只会使事情复杂化,并使底层代码的简单性变得模糊。

On iterators. I think iterators are great when applied in appropriate places. The code I'm working with will never change random-access containers into list or something (so iterating with int i is already container agnostic), and will always need the current index. And all the additional code you need to type (iterator itself and the index) just complicates matters and obfuscates the simplicity of the underlying code.

推荐答案

这是所有的 things.size()类型。它不是 int ,而是 size_t (它存在于C ++中,而不是在C中)

It's all in your things.size() type. It isn't int, but size_t (it exists in C++, not in C) which equals to some "usual" unsigned type, i.e. unsigned int for x86_32.

运算符less(<)不能应用于无符号类型,即 unsigned int 两个不同符号的操作数。只有没有这样的操作码,并且标准没有指定,无论编译器是否可以进行隐式符号转换。

Operator "less" (<) cannot be applied to two operands of different sign. There's just no such opcodes, and standard doesn't specify, whether compiler can make implicit sign conversion. So it just treats signed number as unsigned and emits that warning.

这样写是正确的

for (size_t i = 0; i < things.size(); ++i) { /**/ }

或更快

for (size_t i = 0, ilen = things.size(); i < ilen; ++i) { /**/ }

这篇关于如何处理“签名/未签名的不匹配”警告(C4018)?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆