C code targeting x64, as has been previously discussed, should always use size_t instead of int for things like counts and array indexes.
Given that, it would arguably be simpler and less error prone to just standardize on size_t (typedef'd to something shorter) instead of int as the usual integer type across the entire code base.
Is there anything I'm missing? Assuming you don't need signed开发者_JS百科 integers, and you're not storing large arrays of small integers (where making them 32 bits instead of 64 bits could save memory), is there any reason to use int in preference to size_t?
I would say in the contrary, I would prefer something where you fix the size of the integers, uint8_t
... uint64_t
(and sometime soon unit128_t
), and these would be the base types. So you will know what you get.
And other typedef
like size_t
then aliasing to these. You could then simply inspect the typedef
for uintprt_t
and deduce your address width, e.g.
And also, people need signed types for sure.
But the relation could certainly clarified. Already now in the standard, signed types are sort of deduced from the unsigned types. This could be made explicit by forcing a prefix signed
. But for sure the later wouldn't happen, people are too much emotionally attached to int
:)
As Eli says, int is usually (not always) the word size, i.e. the preferred unit for moving objects around memory and the CPU. Thus, even if you ignore memory usage, you may still get better performance.
Thus, I think it is quite reasonable to use long as the "regular" signed integral type, when you don't need a range bigger than +/- (2^15 - 1), or a particular width.
Using size_t
"for counts" and as a generic unsigned integer type is almost always a design error. size_t
is only enough to hold the size of the largest continuous object supported by the platform. This immediately means that it can be fairly reasonably used as a count of bytes in an object or a count (or index) of elements in an array (since array is always a continuous object). But once we get rid of the continuity requirement, size_t
no longer works. You can't meaningfully use size_t
to count elements in a linked list, since in general case the range of size_t
will not be sufficient.
Of course, using size_t
for such purposes is also wrong conceptually. size_t
implements the concept of object size, not the concept of object count. Using size_t
for array indexing is only justified for abstract arrays. Using size_t
for indexing concrete application-specific arrays is, well, weird.
I personally prefer using unsigned
for counts and array indexing (unless I have a more specific type for that purpose) assuming that the range of the type is sufficient within the domain of my application.
精彩评论