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:
// Adapted from clang-tidy readability-container-size-empty upstream test:
// clang-tools-extra/test/clang-tidy/checkers/readability/container-size-empty.cpp
#include <vector>
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;