What is the purpose of the size_t and ssize_t commands in C?

Asked

Viewed 2,568 times

8

What is the purpose of commands size_t and ssize_t? What kind of data they represent?

size_t minhavariavel1;
ssize_t minhavariavel2;

2 answers

10


Technically they are not commands. They are data types. It is true that in the context the type is serving as a statement (statement) and this is translated by many people as command.

size_t is essentially the same as a int unmarked which is used to store the return of a sizeof, but it may be different on some platform or compiler, it is not required to be this is required to be at least the size of a int.

ssize_t a flagged integer and is used in situations where the same representation of the data size can return a negative value in the event of failure. It is outside the ANSI standard of C, so avoid its use.

Even if they are whole, it is ideal to keep them separate. Each type with its function, gives more semantics to the data and avoids future problems if it needs to make some change.

  • The int also works with negative values, but when I want to treat an error of a function that returns -1 I use the ssize_t that’s msm?

  • 3

    No. It is used to represent the data size. The fact that it is equivalent to int it’s just a coincidence.

7

size_t is defined in the standard C (in stddef.h). ssize_t is the version Signed of size_t, but is defined in a POSIX extension, so it may not exist on all platforms.

The size_t represents the size of something (quantity), and how it is unsigned does not represent negative values. The ssize_t, for being Signed, may also represent such values. For example, the result of a function may be the size of the parameter (if zero / positive) or an error code (if negative).

  • I can use them where I will work only with positive values?

  • 2

    Nothing prevents you from using where you want but I try to use size_t only to represent sizes and unsigned int for positive values in general. In practice it doesn’t make much difference but helps in readability.

  • Why you use unsigned int only for variables with positive values?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.