patterncppMinor
What might be another way to test if int is 32 bits wide at compile time?
Viewed 0 times
mightwhatcompilebitswaywidetimetestanotherint
Problem
Below is code that will compile when
INT_MAX is equal to 232. It will generate a compiler error when INT_MAX is not equal to 232.#include
#include
namespace NBitCheck
{
template struct CTAssert;
template<> struct CTAssert {};
constexpr bool intbitwidthcheck=INT_MAX-(2^32)+1;
CTAssert a;
}
int main(void) {
return 0;
}Solution
In C++,
So,
Next, we need to know how many bits each char has.
So try this:
Frankly, I believe this way is more readable.
Not to mention, can one reasonably expect a 32-bits signed int to contain values up to
sizeof returns the size of a number relative to the size of char.So,
sizeof(int) should give you how many chars each int takes.Next, we need to know how many bits each char has.
CHAR_BIT has that information.So try this:
constexpr size_t bits_per_int = sizeof(int) * CHAR_BIT;
constexpr bool intbitwidthcheck = (bits_per_int == 32);Frankly, I believe this way is more readable.
Not to mention, can one reasonably expect a 32-bits signed int to contain values up to
2^32 - 1? Shouldn't that be the UINT_MAX? INT_MAX should be up to 2^31 - 1.Code Snippets
constexpr size_t bits_per_int = sizeof(int) * CHAR_BIT;
constexpr bool intbitwidthcheck = (bits_per_int == 32);Context
StackExchange Code Review Q#40046, answer score: 7
Revisions (0)
No revisions yet.