简体   繁体   中英

Use `size_t` as the type for a counter

Is it appropriate to use size_t instead of int or unsigned as the type for a counter?

The following code is grasped from C++ Primer .

size_t count_calls()
{
    static size_t ctr = 0;
    return ++ctr;
}

int main()
{
    for (size_t i = 0; i != 10; ++i)
        cout << count_calls() << endl;
    return 0;
}

I know that size_t is a good choice for size, array indexing, but what about when it comes to a plain counter? (as in the count_calls function.) Are there any difference?

size_t is a type that is appropriate to count elements in an array and, therefore, in any array-based container. However, size_t is, conceptually, insufficient to count elements in a non-array-based container. (Eg size_t is not guaranteed to be wide enough to count elements of std::list .) For this reason, in general case, it is inappropriate to use size_t as a generic counter type. And obvious example would be a segmented memory model, under which size_t might easily end up being relatively narrow compared to the capacity of the platform itself.

If you really want to find a generic type that is wide enough for most real-life cases, that would be uintptr_t perhaps. And again, the choice in this case is based on the fact that uintptr_t should be sufficiently wide to count anything that can fit in memory. However, for obvious reasons, it might still prove to be too small to count something more extensive.

I'd also add that using such generic types as size_t and unitptr_t as counters in application-specific code might be considered a questionable programming practice, since they don't convey any application-specific semantics. They are more memory-oriented than generic-counter-oriented.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM