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()
)?
CodePudding user response:
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
CodePudding user response:
I would encourage you to cast from size_t
to int
and performing the arithmetic on the int
s.
You can also cast with a shorter syntax like this int(someThing.size())
.