g ++警告:无符号表达式的比较< 0总是假的 [英] g++ warning: comparison of unsigned expression < 0 is always false

查看:343
本文介绍了g ++警告:无符号表达式的比较< 0总是假的的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了编译我的C ++代码,我使用了 -W 标志,这会导致警告:


警告:无符号表达式的比较< 0总是假的

我相信这被认为是一个bug,并且在GCC 4.3版本中修复了,但是我使用的是GCC 4.1



明显冒犯这里的代码:

  void FieldGroup :: generateCreateMessage(const ApiEvent :: GroupData& data,omsgstream& result)const {
dblog<<调试;

//按照指定的顺序写出我们关心的数据字段
for(size_t index = 0; index< fields.size(); ++ index){
size_t esIndex = clsToES [index];
if(esIndex< 0 || esIndex> = data.fields.length()){
ostringstream buf;
buf<< 无效字段<<索引<< (ES数据集中的索引<<<<<<<<<<<<<<<<<<<"<"
throw InvalidDataException(buf.str());
}
fields [index] .writeData(data.fields [esIndex],result);


警告我收到:


dbtempl.cpp:在成员函数'void ECONZ :: FieldGroup :: generateCreateMessage(const nz :: co :: econz :: eventServer :: ApiEvent :: GroupData&; ECONZ :: omsgstream&)const':
dbtempl.cpp:480:警告:无符号表达式的比较< 0始终为false


我怎样才能阻止这些警告出现?我不想删除 -W 标志。

解决方案

您正在测试一个正值是否低于0.

A size_t 是无符号的,因此至少为0.



这可以从不发生,并且编译器通过删除测试来优化事情。警告在这里告诉你,因为如果有人这样做,这可能是一个错误。

在你的情况下,你可能只是删除测试,应该没问题。

To compile my C++ code I use the -W flag, which causes the warning:

warning: comparison of unsigned expression < 0 is always false

I believe this was considered as a bug and was fixed on version GCC 4.3, but I'm using GCC 4.1

Code that is obviously offending here:

void FieldGroup::generateCreateMessage (const ApiEvent::GroupData &data, omsgstream &result) const {
  dblog << debug;

  // Write out the data fields we care about, in the order they were specified
  for (size_t index = 0; index < fields.size(); ++index) {
    size_t esIndex = clsToES[index];
    if (esIndex < 0 || esIndex >= data.fields.length()) {
      ostringstream buf;
      buf << "Invalid field " << index << " (index in ES data set " << esIndex << ", " << data.fields.length() << " fields returned)";
      throw InvalidDataException (buf.str());
    }
    fields[index].writeData (data.fields[esIndex], result);
  }
}

Warning I'm getting:

dbtempl.cpp: In member function ‘void ECONZ::FieldGroup::generateCreateMessage(const nz::co::econz::eventServer::ApiEvent::GroupData&, ECONZ::omsgstream&) const’: dbtempl.cpp:480: warning: comparison of unsigned expression < 0 is always false

How can i possibly stop these warnings from appearing? I don't want to remove the -W flag.

解决方案

You are testing if a positive value is below 0.

A size_t is unsigned, so at least 0.

This can never happen and the compiler optimize things out by just removing the test. The warning is here to tell you because if someone does that, it might be a mistake.

In your case, you might just remove the test, it should be fine.

这篇关于g ++警告:无符号表达式的比较&lt; 0总是假的的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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