Reputation: 1225
I want to safely compare an ssize_t
variable with an 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
Upvotes: 1
Views: 724
Reputation: 45684
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
Upvotes: 5
Reputation: 41962
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
Upvotes: 4
Reputation: 415
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;
Upvotes: -4