1

I am currently learning C++ and I saw there was a line of codes writing on the textbook:

ssize_t num = index; // index could be -1 in the example of my textbook`

The num is a variable to contain the index return from a traversing. However,after I copy this code to my C++ compiler, it says it can not find the definition of ssize_t. And I can hardly find there is any definitions about ssize_t in C++. I saw that it could be use in C but not C++. Right?

Ricky_Lab
  • 21
  • 5
  • 4
    That data type identifier isn't built into either C or C++, both of them need the correct #include. – Ben Voigt Apr 07 '22 at 21:11
  • `#include ` (probably, at least on every POSIX system I've ever worked on). – WhozCraig Apr 07 '22 at 21:12
  • @WhozCraig: The [official POSIX aka Single Unix Specification agrees](https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/sys_types.h.html) – Ben Voigt Apr 07 '22 at 21:14
  • If you want a standard drop-in (most likely) replacement for `ssize_t` you could use [`std::ptrdiff_t`](https://en.cppreference.com/w/cpp/types/ptrdiff_t) which is what [`std::ssize()`](https://en.cppreference.com/w/cpp/iterator/size) and [`ranges::ssize()`](https://en.cppreference.com/w/cpp/ranges/ssize) returns. It is _"used for pointer arithmetic **and array indexing, if negative values are possible**_" – Ted Lyngmo Apr 07 '22 at 21:14
  • Sorry for explain my question not clearly enough, I edited my question again. `num` is for index, which could be -1 or positive index. I just try to change it to `size_t` but I think it is not suitable because `size_t` could not be negative. – Ricky_Lab Apr 07 '22 at 21:14
  • 1
    It cannot find the definition because you didn't #include the right file. Add `#include ` and it will find the definition (if you are on a POSIX platform or any other platform that has a `sys/types.h`). If you need portability to all C and C++, not only POSIX, use `ptrdiff_t` as @TedLyngmo suggested. That also needs a `#include ` to work. – Ben Voigt Apr 07 '22 at 21:15

1 Answers1

3

ssize_t can (and cannot) be used in C++ just as much as it can (and cannot) be used in C. There is no fundamental type by such name in either language, and there is no ssize_t type in the ISO C standard library, nor is there a std::ssize_t in the C++ standard library.

ssize_t is defined in the POSIX standard. If your program is compiled for a POSIX system, then you can use ssize_t by including the header from the POSIX library that defines it. On non POSIX system, such header doesn't exist, so this is not portable. You shouldn't use ssize_t in a cross platform program except in a POSIX specific module that uses the POSIX API.

When you aren't using the POSIX API, you can typically substitute ssize_t with std::ptrdiff_t.

eerorika
  • 232,697
  • 12
  • 197
  • 326