简体   繁体   中英

why does UINT_MAX + 3 always equal 2?

Can someone help me, I've written a small C program to output the value of UINT_MAX + 3, and tested it on both a mac, and ubuntu, and it keeps giving me 2

Thank you

It is the way it is defined in th C standard. Unsigned integers have modular arithmetic. Incrementing the largest unsigned integer of any type by 1 results in 0. Incrementing by 2 yields 1. And so on.

By the same token, subtracting 1 from 0 gives you the largest value of that unsigned integer type.

If you actually want to add 3 to UINT_MAX and obtain a larger value, then you need to use a larger integer type than the type for which UINT_MAX is defined for your compiler. Unfortunately, the way that you do that depends on your compiler. For example using Visual C++ on Windows, an int is 32 bits, so UINT_MAX is 4,294,967,295. In Visual C++, you specify a 64-bit integer using the type __int64, so writing:

unsigned __int64 n;
n=(unsigned __int64)UINT_MAX+3;
printf("%I64i\n",n);

...will print the desired value, 4,294,967,298.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM