Strange warning in C++11 range based for loop
Jonathan Wakely
jwakely.gcc@gmail.com
Tue Aug 30 14:12:00 GMT 2011
On 30 August 2011 14:58, Pavel Dzhioev wrote:
> Hello!
> I have some class, that allows to iterate through numeric range.
> For example code:
>
>> for (int i: range(N)) {
>> cout << i << endl;
>> }
>
> works fine. But if I try repeatedly do some action:
>
>> for (int i: range(N)) {
>> doSomething();
>> }
>
> compiler gives me warning:
>
>> warning: unused variable `i' [-Wunused-variable]
That's because the variable 'i' is not used after it's declared.
> But at same time classic for-loop:
>
>> for (int i =3D 0; i < N; ++i) {
>> doSomething();
>> }
>
> compiles without warnings.
That's because the variable 'i' is used.
> My compiler's version is "g++-4.6 (GCC) 4.6.1", compiler flags
> "--std=c++0x -Wall"
> I'm wondering, is it planned behavior or bug?
I don't think it's a bug, since the -Wunused-variable warning is
behaving exactly as it's designed to: you declared a variable 'i' and
never used it.
You could file an enhancement request in Bugzilla requesting that the
warning is disabled for the variable in the for-range-declaration.
To suppress the warning in your code you can do:
for (int __attribute__((unused)) i : range(N))
Or:
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
for (int i : range(N))
doSomething();
#pragma GCC diagnostic pop
More information about the Gcc-help
mailing list