简体   繁体   中英

How to safely compare a ssize_t with a int64_t

I want to safely compare a ssize_t variable with int64_t variable to check if the values are equal. By safe I mean the comparison should work for any value of ssize_t . My first guess is to use a static_cast to convert the ssize_t to int64_t but I'm not sure if it is a safe way to convert?

Something like:

ssize_t a = read(...);
int64_t b = getsize(...);
if(static_cast<int64_t>(a) == b){
  // ... read succeeded
} else{
  // ... partial or read failure
}

Update: On Ubuntu, they both are of exactly the same size

Don't over-complicate things.

ssize_t and int64_t are both signed types, thus the common type is the bigger of the two, meaning the conversion is value-preserving.
In conclusion, directly using the comparison-operator will do the right thing .

You only have to take care when mixing signed and unsigned, with the unsigned being at least as big as int and the signed type. Because only in that case conversion to the common type won't be value-preserving for negative values.
In that case, C++20 helps with intcmp

In C++20 you don't even need to care about signness or the size of the operands, just use intcmp to do the comparison

if (std::cmp_equal(a, b)) {
  // ... read succeeded
} else{
  // ... partial or read failure
}

There's also std::in_range to check values regardless of type and signness

most of the time you don't have ssize_t . and when you do what stops you from doing

int64_t a;
ssize_t b;
b = sizeof(ssize_t) == sizeof(int64_t) ? a : whatever_else;

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