When to use size_t?

8

Now research the subject, but I always get confused. I found a article in English that explains very well some reasons for the existence of the type and how to use it. In this article the type is meant to represent sizes in bytes of objects, however I always see in books and codes using the size_t type in several places that do not represent sizes.

So when should I use size_t and what advantages can this use bring?

    
asked by anonymous 20.04.2015 / 22:54

3 answers

4

You do not really have an exact moment that you should use size_t. Because it is the same as 'unsigned int' you use it anywhere you would use an 'unsigned int', the only difference is that an 'unsigned int' is more appropriate for sizes, since it is an unsigned, all its values that would be negative go to the space of the positive values which is better since practically one does not measure size in bytes with negative values. And the advantage of using int type is that sizes in bytes are measured in integer numbers, not decimals, so it would be pointless to use float or double.

The size_t was made more specifically to be used as a result of the sizeof operator, but it is also generally used for indexing arrays and counter loops (for, while) operations that do not usually use negative or decimal values. / p> So basically, the advantage of using size_t is the same as using 'unsigned int' in the appropriate place, but for the sake of organization, size_t is more used to represent sizes, after all, it would not make sense to use it for other purposes if we can use 'uint32_t' which represents the same thing.

    
23.04.2015 / 03:41
4

I use basically 2 situations

1) sizes for allocation

size_t len;
// calcula len
ptr = malloc(len * sizeof *ptr);

2) for indexing arrays

for (size_t i = 0; i < sizeof array / sizeof *array; i++) {
    // work with array[i];
}
    
20.04.2015 / 23:07
2

size_t is a typedef for unsigned int. So any situation that fits your use, is valid and you can use. Of course by looking at the maximum limits for the situation.

Historically, this definition was made for indexing vectors, loops as well as for the result of using the sizeof operator.

However, it can be understood as any type and used without problem in any situation that is plausible.

    
04.05.2015 / 18:21