Cython: (Why / When) Is it preferable to use Py_ssize_t for indexing?

Py_ssize_t is signed. See PEP 353, where it says “A new type Py_ssize_t is introduced, which has the same size as the compiler’s size_t type, but is signed. It will be a typedef for ssize_t where available.” You should use Py_ssize_t for indexing. I didn’t find a definitive statement of this in the Cython docs, … Read more

Why are unsigned integers error prone?

One possible aspect is that unsigned integers can lead to somewhat hard-to-spot problems in loops, because the underflow leads to large numbers. I cannot count (even with an unsigned integer!) how many times I made a variant of this bug for(size_t i = foo.size(); i >= 0; –i) … Note that, by definition, i >= … Read more

Why is size_t unsigned?

size_t is unsigned for historical reasons. On an architecture with 16 bit pointers, such as the “small” model DOS programming, it would be impractical to limit strings to 32 KB. For this reason, the C standard requires (via required ranges) ptrdiff_t, the signed counterpart to size_t and the result type of pointer difference, to be … Read more

A warning – comparison between signed and unsigned integer expressions

It is usually a good idea to declare variables as unsigned or size_t if they will be compared to sizes, to avoid this issue. Whenever possible, use the exact type you will be comparing against (for example, use std::string::size_type when comparing with a std::string‘s length). Compilers give warnings about comparing signed and unsigned types because … Read more