Quuxplusone / LLVMBugzillaTest

0 stars 0 forks source link

false positive, unused loop variable #23415

Open Quuxplusone opened 9 years ago

Quuxplusone commented 9 years ago
Bugzilla Link PR23416
Status CONFIRMED
Importance P normal
Reported by ncm (ncm@cantrip.org)
Reported on 2015-05-05 12:01:37 -0700
Last modified on 2021-03-20 17:47:34 -0700
Version unspecified
Hardware PC Linux
CC davidfromonline@gmail.com, dgregor@apple.com, llvm-bugs@lists.llvm.org
Fixed by commit(s)
Attachments
Blocks
Blocked by
See also
struct range {
    int start; int stop;
    struct iter {
        int i;
        bool operator!=(iter other) { return other.i != i; };
        iter& operator++() { ++i; return *this; };
        int operator*() { return i; }
    };
    iter begin() { return iter{start}; }
    iter end() { return iter{stop}; }
};
int main()
{
   int power = 1;
   for (int i : range{0,10})
       power *= 10;
}
bug.cc:15:13: warning: unused variable 'i' [-Wunused-variable]
   for (int i : range{0,10})

Manifestly, i is used to count loop iterations.  The warning cannot be
suppressed by any decoration of the declaration; the best we can do is

  void(i), power *= 10;

in the loop body.  The warning is useful in most cases.  The exception might be
that, here, the iterator has no reference or pointer members, and the loop body
changes external state.
Quuxplusone commented 9 years ago

This matches gcc bug https://gcc.gnu.org/bugzilla/show_bug.cgi?id=66028

Quuxplusone commented 3 years ago

See it live: https://godbolt.org/z/q8czzh

The workaround since C++17 is to modify your for loop to be

for ([[maybe_unused]] int i : range{0,10})

but I agree this warning is annoying when trying to use an integer range.