1

I need to have an int variable go up to 4294967295 (0xFFFFFFFF), without using unsigned and long, so it can actually be used by other functions. Is that even possible?

5
  • 1
    Yes, if you can find or create a compiler that support that.
    – MikeCAT
    Nov 4, 2020 at 16:32
  • 2
    It is possible only if your platform has an int larger than 32 bit. If your platform has 32 bit int then it cannot represent 4294967295. Why are you trying to avoid unsigned? It would fix your problem. Nov 4, 2020 at 16:33
  • Dirty but widely used hack: #define int long long ... Oops, this uses long. Then #define int int64_t
    – MikeCAT
    Nov 4, 2020 at 16:33
  • 2
    What are you trying to achieve? Why you can't use unsigned int? What does 'used by other functions' mean?
    – SergeyA
    Nov 4, 2020 at 16:34
  • 1
    @MikeCAT: Alas the behaviour of doing that is undefined.
    – Bathsheba
    Nov 4, 2020 at 16:34

2 Answers 2

3

You can't, unless you find a platform with an int that's larger than 32 bits (they are at the time of writing rare).

If you need to use a signed type, then std::int64_t is a good choice. Or long long is also guaranteed to be large enough.


If you're absolutely constrained by the interface to your function then you could break your number up into two parts - and adopt the convention that you need to call the function twice to get anything meaningful out of it. But that could make your program very brittle.


Another option: if your function is allowed to take the int by reference then you could have an array of two ints at the call site, and pass the first one to your function. You can then reach the other using pointer arithmetic within the function body! Again, this will make your code brittle but it would work.

4
3

You can't. Because: an int value is defined as 31 bits plus one leading bit as a sign.

You can push whatever you want into the 32 bits of an int, as long as it is declared as int, the leading bit will always be interpreted as the sign.

1
  • 1
    Be careful: not necessarily. Although from C++20, int has to be a 2's complement type, with a minimum range [-32768, 32767]
    – Bathsheba
    Nov 4, 2020 at 16:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.