spaL
spaL

Reputation: 686

C++ size_t in mixed arithmetic and logical operations

Currently using WSL2, g++, with -std=c++20 -Wall -Wextra -Wvla -Weffc++ -Wsign-conversion -Werror.

In the program I'm building, because I utilize several STL containers such as std::vector, std::array, std::string, etc, I've come across many situations involving integer arithmetic or logical comparisons between size_t (from .size() or .length()) and signed values.

To avoid errors from occuring, I have changed values (that "I think" should generally always be positive) into unsigned values, either by changing the variable definition, or using static_cast<size_t>() (which make my code lines especially long). But now I'm encountering more and more underflow errors.

Should I change all the variables back to signed types and use assertions to see if they go negative? What are some efficient ways to conduct integer arithmetic and logical comparisons between signed integers and unsigned integers (especially from .size())?

Upvotes: 0

Views: 355

Answers (1)

康桓瑋
康桓瑋

Reputation: 42776

Instead of calling the member function size(), you can use C++20 std::ssize() to get the signed size for comparison and operation with signed integers.

std::vector v{42};
auto size = std::ssize(v); // get signed size

Upvotes: 5

Related Questions