Using ssize_t vs int

只谈情不闲聊 提交于 2019-11-28 20:14:54

There's no guarantee in the C or POSIX standards that sizeof(int) >= sizeof(ssize_t), nor the other way around. Typically ssize_t is larger than int, but the safe and portable option in C99 is to use intmax_t instead for the argument and the return value.

The only guarantees you have wrt. the relationship between int and ssize_t are:

  • int can store values of at least the range [-2^15 ... 2^15-1] per ISO C
  • ssize_t can store values of at least the range [-1 ... 2^15-1] per POSIX (see _POSIX_SSIZE_MAX).

(Interestingly, there isn't even a guarantee that ssize_t can store the negative counterparts of its positive range. It's not a signed size_t, but a "size type" with an error value.)

Use types in a way:

  • you don't mix signed and unsigned types together and
  • you don't truncate values from larger types while storing them in smaller types (overflow/underflow)

ssize_t might be an alias for int, yet it is not standard C and might be environment specific.

If your program will run in specific environment, check whether sizeof(ssize_t) <= sizeof(int) and use int. Otherwise, use some other type T where sizeof(T) is greater or equal than both sizeof(int) and sizeof(ssize_t).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!