Strange question about two equal values

Can (value+1) be equal to value? Find an algorithm that can verify it.

Now, this question is quite vague. I assume that value is a int/float/double.

The only answer I can find is: it's true only when value=INT_MAX, so INT_MAX+1= INT_MAX.

How would you answer?
For a signed integer, INT_MAX + 1 would engender undefined behaviour (signed integer overflow).

For floating point types, NaN + 1 yields NaN.
However, NaN is unordered: it is not equal to, greater than, or less than anything, including itself.

(value+1) == value can be true if value is of a user defined type.
Can (value+1) be equal to value?

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(); }
bool operator==(A, A) { return true; }

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++.
Last edited on
1
2
3
4
5
6
7
8
9
#include <iostream>
using namespace std;

int main()
{
   bool value = 1;
   bool valuePlusOne = value + 1;
   cout << "Is value equal to value + 1? " << boolalpha << ( value == valuePlusOne ) << '\n';
}
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.

Yes, that is a good point.
Topic archived. No new replies allowed.