Compare with empty() instead of size()

ID

c.maintainability.container_size_empty

Severity

low

Remediation Complexity

trivial

Remediation Risk

low

Remediation Effort

low

Resource

Idiom

Language

C / C++

Description

Checking emptiness through size() is less clear and, for some containers (e.g. std::list), potentially O(n). Use the empty() method, which is constant-time and states the intent directly (c.empty() / !c.empty()).

Rationale

Checking emptiness through size() is less clear and, for some containers (e.g. std::list), potentially O(n). Use the empty() method, which is constant-time and states the intent directly (c.empty() / !c.empty()).

The following code illustrates the pattern detected by this rule:

bool checks(const std::vector<int> &vect) {
  // FLAGGED: Compare with empty() instead of size()
  if (vect.size() == 0)
    return true;
  // FLAGGED: Compare with empty() instead of size()
  if (0 == vect.size())
    return true;
  // FLAGGED: Compare with empty() instead of size()
  if (vect.size() != 0)
    return true;
  // FLAGGED: Compare with empty() instead of size()
  if (vect.size() > 0)
    return true;
  // FLAGGED: Compare with empty() instead of size()
  if (vect.size() < 1)
    return true;

  if (vect.size() > 1)
    return true;
  if (vect.size() <= 1)
    return true;
  if (vect.size() == 3)
    return true;
  if (vect.empty())
    return true;
  return false;
}

Remediation

Follow secure coding practices and review the references below for detailed remediation guidance.

Configuration

This detector does not need any configuration.

© 2026 Xygeni. All rights reserved