You want to be able to do e.g. for i in 1:10
# Not for i in UInt(1):UInt(10)
or even use: 0x0000000000000001:0x000000000000000a
Note, Int (and integer literals), is 64-bit in Julia (except on 32-bit platforms, then 32-bit). That means the 1 bit lost to the sign isn’t a huge deal, i.e. 63 bits indexing is enough (on 32-bit it’s 31-bit indexing). Historically in C/C++ 16-bit indexing was much better than 15-bit that signed would have given (only 32767 indexes, half your memory likely; Julia doesn’t officially support 8- or 16-bit platforms, but HAS been run on 8-bit Arduino, then Int is still not smaller than 32-bit). Note the implication “bit width of std::ptrdiff_t is not less than 17” which seems awkward, in practice likely means “not less that 32”.
Int, as signed, is much better in general (e.g. for literals), unsigned is a potential trap.
That’s true in C++, but not in general with Julia. While, by default, arrays start at 1, they can start at an arbitrary index, e.g. -1, when using OffsetArrays
(you can also do similar in Fortran), and it can be very practical. See also… unpractical/joke (that I doubt you can do in Fortran):
If you declare your i
index signed (implicitly, as you do), and would index with it as an unsigned, then you can cast with i % UInt64
, implicitly or explicitly, but while that way it’s fast, you use loose out on bounds-checking, or you would check for negative numbers, an extra check slowing down (though it might bet optimized away since redundant with the check i < 1
).
Using unsigned, unsigned int, int (or even size_t it, seems in, extreme cases) is a potential bug in C/C++:
The bit width of size_t is not less than 16. (since C99)
https://en.cppreference.com/w/cpp/types/size_t
On many platforms (an exception is systems with segmented addressing) std::size_t can safely store the value of any non-member pointer, in which case it is synonymous with std::uintptr_t.
std::size_t is commonly used for array indexing and loop counting. Programs that use other types, such as unsigned int, for array indexing may fail on, e.g. 64-bit systems when the index exceeds UINT_MAX or if it relies on 32-bit modular arithmetic.
When indexing C++ containers, such as std::string, std::vector, etc, the appropriate type is the member typedef size_type provided by such containers. It is usually defined as a synonym for std::size_t.
The integer literal suffix for std::size_t is any combination of z or Z with u or U (i.e. zu, zU, Zu, ZU, uz, uZ, Uz, or UZ). (since C++23)
https://en.cppreference.com/w/cpp/types/ptrdiff_t
std::ptrdiff_t is the signed integer type of the result of subtracting two pointers.
The bit width of std::ptrdiff_t is not less than 17. (since C++11)
Notes
std::ptrdiff_t is used for pointer arithmetic and array indexing, if negative values are possible. Programs that use other types, such as int, may fail on, e.g. 64-bit systems when the index exceeds INT_MAX or if it relies on 32-bit modular arithmetic.