C++ size_t or ptrdiff_t

c++

Solution

std::ptrdiff_t is signed. std::size_t is unsigned. Casting `strlen(p)` to `ptrdiff_t` would make sense if `p` could have a negative length, which is not possible.

However, that cast could overflow the resulting signed value if `p` is large enough (for instance, larger than 2,147,483,647 bytes on most 32-bit platforms). So it could introduce an error in your pointer arithmetic.

Best to stick with `size_t` here.

Problem

If you have the following code where p is a pointer: ``` p = p + strlen(p) + size_t(1); ``` Since `strlen()` and `size_t` are both `size_t`, should I cast the code to `ptrdiff_t` ? ``` p = p + (ptrdiff_t)(strlen(p) + size_t(1)); ``` If so why? Thanks, Greg

Original source