Skip to content

False positive "for loop analysis" warning #109402

Open
@rHermes

Description

@rHermes

This is tested with clang 18.1.0 on godbolt and occurs on trunk.

Here is the godbolt: https://godbolt.org/z/o3jhnoPso

Here is the code:

#include <iostream>
#include <vector>

/**
 * Definition for singly-linked list.
 */
struct ListNode
{
  int val;
  ListNode* next;
  ListNode() : val(0), next(nullptr) {}
  ListNode(int x) : val(x), next(nullptr) {}
  ListNode(int x, ListNode* next) : val(x), next(next) {}
};

class Solution
{
public:
  static std::vector<std::vector<int>> spiralMatrix(const int M, const int N, ListNode const* head)
  {
    std::vector<std::vector<int>> out(M, std::vector<int>(N, -1));

    const auto writeVal = [&](const int y, const int x) {
      if (head) {
        out[y][x] = head->val;
        head = head->next;
      }
    };

    // ok, we will loop in numbers.
    for (int iter = 0; head; iter++) {
      const int W = N - 2 * iter;
      const int H = M - 2 * iter;

      for (int j = 0; j < W; j++) {
        writeVal(iter, iter + j);
      }

      for (int j = 1; j < H; j++) {
        writeVal(iter + j, iter + W - 1);
      }

      for (int j = W - 2; 0 <= j; j--) {
        writeVal(iter + H - 1, iter + j);
      }

      for (int j = H - 2; 0 < j; j--) {
        writeVal(iter + j, iter);
      }
    }

    return out;
  }
};

If you compile this like so you get the following warning:

clang++ -Wall -Wextra -std=c++2a -Werror -o test test.cpp
<source>:31:24: error: variable 'head' used in loop condition not modified in loop body [-Werror,-Wfor-loop-analysis]
   31 |     for (int iter = 0; head; iter++) {
      |                        ^~~~

Metadata

Metadata

Assignees

No one assigned

    Labels

    clang:diagnosticsNew/improved warning or error message in Clang, but not in clang-tidy or static analyzerfalse-positiveWarning fires when it should not

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions