-1

i have a question about relational operators are they always give correct results ? because if we run this line of code it will result 1 instead of 0

cout<<(ULLONG_MAX==-1);

and if we keep subtracting 1 of both sides it will keep resulting 1

so this could give wrong results in our programs

what is the solution to it?

πάντα ῥεῖ
88.9k13 gold badges125 silver badges199 bronze badges
asked Nov 7, 2023 at 20:30
4
  • 3
    Since one is explicitly unsigned and the other is signed, what exactly is your expectation, and why? Commented Nov 7, 2023 at 20:34
  • i expect that it gives 0 because it should be handled in the language if that is only the problem its okay but its the same with other numbers too Commented Nov 7, 2023 at 20:41
  • @Mohamad_T ??????? Commented Nov 7, 2023 at 21:14
  • For fun, do this: unsigned long long one = 1; if (one < -1) cout << "How can 1 be less than -1?\n"; Commented Nov 7, 2023 at 22:13

2 Answers 2

5

In this comparison

ULLONG_MAX == -1

You have one unsigned long long and one int. Before the values are being compared, the operands undergo integral promotion in which the int is promoted to unsigned long long, which is like doing static_cast<unsigned long long>(-1) so that the two operands have a common type.

Now, an unsigned long long can't hold the value -1 and it will then "wrap around" to become the largest possible unsigned long long - which is exactly the value ULLONG_MAX holds.

The comparison is therefore true and printing true will show 1 (unless std::boolalpha is in effect).

answered Nov 7, 2023 at 20:44
Sign up to request clarification or add additional context in comments.

1 Comment

ok i understand now i will make a function to handle this case thank you so much.
2

Since you are looking for solutions:

Enabling warnings (-Wall or more specifically -Wsign-compare on clang or gcc) should give you a warning if you accidentally do this:

warning: comparison of integers of different signs: 'unsigned long long' and 'int' [-Wsign-compare]

And the fix is to make sure everything has the same type.

If you really meant to compare two objects of different types, you can use std::cmp_equal (or the example implementation if you can't use C++20):

std::cout << std::cmp_equal(ULLONG_MAX, -1); // Outputs 0

which directly compares the values of the integers, regardless of the type.

answered Nov 7, 2023 at 21:17

1 Comment

Cool. I had missed that cmp_equal and friends had appeared in the library!

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.