如何使g ++对int i = i生成错误/警告? [英] how to make g++ generate an error/warning for int i = i?

查看:108
本文介绍了如何使g ++对int i = i生成错误/警告?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很难在代码中找到由如下循环引起的错误:

I had a hard time to find a bug in my code caused by a loop like this:

for (int i=i;i<5;i++){
    // ...
}

我将g ++ 4.7.2与 -O2 -Wall 一起使用,但未显示警告/错误。是否有一些编译器标志还与 -O2 结合使用会为这种情况创建警告?

I use g++ 4.7.2 with -O2 -Wall, but no warning/error is shown. Is there some compiler flag that also in combination with -O2 creates a warning for such a case?

我发现了几个相关的问题:
在评论中此处在讨论中,当没有 -O2 时,g ++将显示 -Wall 的警告。但是,这个问题特别重要,因为问题循环已使用 -O2 进行了优化,这可以解释为未显示警告。就我而言,循环并没有得到优化,但仍然没有得到警告。
也与此相关的是这个问题这一个。阅读完这些问题之后,我了解了为什么c ++允许这种废话(我喜欢此处的示例,因为它根本不是废话),但我仍在寻找一个编译器标志,该标志也将与 -O2 一起创建警告。

I found several related questions: here in the comments it is discussed, that g++ shows a warning with -Wall when there is no -O2. However, that question is particular because the problematic loop is optimized away with -O2 which would explain that no warning is shown. In my case the loop is not optimized away, but still I get no warning. Also related is this question and this one. After reading those questions, I understand why c++ allows such non-sense (I like the example here because it isnt nonsense at all), but I am still looking for a compiler flag that would create a warning also with -O2.

推荐答案

在编译时,clang编译器给了我

The clang compiler gives me, when compiling

int main()
{
    int j = 0;
    for (int i=i; i<5; ++i)
        j++;
    return 0;
}

带有 -O2 -Wall

warning_loop.cxx:4:16: warning: variable 'i' is uninitialized 
when used within its own initialization [-Wuninitialized]
 for (int i=i; i<5; ++i)

gcc(5.3版)编译器也会发出警告:

The gcc (version 5.3) compiler gives a warning as well:

warning_loop.cxx: In function 'int main()':
warning_loop.cxx:4:16: warning: 'i' is used uninitialized in 
this function [-Wuninitialized]
 for (int i=i; i<5; ++i)

未初始化值的使用可以通过valgrind跟踪

The usage of uninitialized values can be traced with valgrind

valgrind --track-origins=yes ./a.out

提供输出:

==33052== Memcheck, a memory error detector
==33052== Copyright (C) 2002-2015, and GNU GPL'd, by Julian Seward et al.
==33052== Using Valgrind-3.11.0 and LibVEX; rerun with -h for copyright info
==33052== Command: ./a.out
==33052== 
==33052== Conditional jump or move depends on uninitialised value(s)
==33052==    at 0x100000F8C: ??? (in ./a.out)
==33052==    by 0x10022F5AC: start (in /usr/lib/system/libdyld.dylib)
==33052==  Uninitialised value was created by a stack allocation
==33052==    at 0x7FFF5FC01036: _dyld_start (in /usr/lib/dyld)

这篇关于如何使g ++对int i = i生成错误/警告?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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