-1

I am under the impression that INT_MAX will turn on all 32 bits of an int. If I negate that and 'and' it with itself, I should be comparing all 0s with all 1s and get back false. What am I missing?

int x = INT_MAX;
x = ~x && INT_MAX;
printf("x = %d\n", x); /*Returns 1*/
x = 0;
x = ~x && INT_MAX;
printf("x = %d\n", x); /*Returns 1*/

Edit: Oh wow I was flipping the sign bit as well. Using UNIT_MAX is giving me the result I needed. Thank you, everyone!

3
  • 1
    I am under the impression that INT_MAX will turn on all 32 bits of an int. - you forgot about the sign bit. Commented Jan 26, 2018 at 21:13
  • 6
    && is logical AND, not bit-wise. Commented Jan 26, 2018 at 21:13
  • 2
    "I am under the impression that INT_MAX will turn on all 32 bits of an int." You are under the wrong impression. Signed values use the MSb for denoting negative values. Commented Jan 26, 2018 at 21:15

2 Answers 2

4

You're working with signed ints here; ~INT_MAX == INT_MIN (edit: for two's complement, which is what every modern processor uses), not 0. In C, all values except 0, including negatives, will evaluate to true when used in a conditional.

If you switch to unsigned types everything should work as expected since ~UINT_MAX == 0.

Sign up to request clarification or add additional context in comments.

10 Comments

~INT_MAX == INT_MIN - I think it is incorrect... Update: Well, correct for 2's complement.
@ChristianGibbons A quick search is bringing this: superuser.com/questions/1137182/… Anyway, it's true in most cases, that's fine.
@EugeneSh. Don't get me wrong, I'm on your side there. The C standard does not guarantee ~INT_MAX == INT_MIN. Won't find many processors these days for which it's not true, but it is always good to be aware of such possibilities. And I'm all for a little pedantry here and there.
I actually think that the real answer to the question is that the OP is using && instead of &... but... OK :)
Hm, I don't think so since OP says "I should be comparing all 0s with all 1s and get back false" in the question, but it's definitely possible…
|
1

I am under the impression that INT_MAX will turn on all 32 bits of an int.

No; it will only turn on the lower 31 bits of an int1 - the uppermost (sign) bit will be left 0 to denote a positive value. ~INT_MAX corresponds to ~0x7FFFFFFF, or 0x80000000.

You're thinking of UINT_MAX.


  1. Assuming a 32-bit int; some implementations may use wider integers.

Comments

Your Answer

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.