Yes, for user defined types you can overload the operators to do whatever you want.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
#include <iostream>
class A {};
A operator+(A, int) { return A(); }
booloperator==(A, A) { returntrue; }
int main()
{
A value;
if (value+1 == value)
{
std::cout << "value+1 is equal to value\n";
}
else
{
std::cout << "value+1 is NOT equal to value\n";
}
}
output:
value+1 is equal to value
It can also happen with big floating-point numbers that doesn't have enough precision so that value+1 gets rounded down to value.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
#include <iostream>
int main()
{
double value = 1e100;
if (value+1 == value)
{
std::cout << "value+1 is equal to value\n";
}
else
{
std::cout << "value+1 is NOT equal to value\n";
}
}
output:
value+1 is equal to value
The only answer I can find is: it's true only when value=INT_MAX, so INT_MAX+1= INT_MAX.
No. The result of integer overflow is not defined in C++.
This is a spurious example: there is loss of information when value + 1 is narrowed to a bool. bool valuePlusOne = { value + 1 }; // *** error: narrowing conversion
If comparison after unbridled narrowing to bool is a valid device, once can also 'prove' that 7 == -999.
Peter87> It can also happen with big floating-point numbers that doesn't have enough precision
> so that value+1 gets rounded down to value.