# What might be another way to test if int is 32 bits wide at compile time?

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 <iostream>
#include <climits>

namespace NBitCheck
{
template<bool> struct CTAssert;
template<> struct CTAssert<true> {};

constexpr bool intbitwidthcheck=INT_MAX-(2^32)+1;
CTAssert<intbitwidthcheck> a;
}

int main(void) {

return 0;
}


In C++, 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.

• One may expect (even though I never saw such architecture) that INT_MAX == UINT_MAX as a border case. What the standard ensures is that The range of non-negative values of a signed integer type is a subrange of the corresponding unsigned integer type, and the value representation of each corresponding signed/unsigned type shall be the same. – Massimiliano Jan 26 '14 at 10:26
• horrible C-style hack. Why not use the C++ features explicitly provided for such purposes? (std::numeric_limits<>) – Walter Jan 30 '14 at 21:11
• @Walter numeric_limits doesn't tell how many bits an int has. If instead of checking how many bits there are you really want the actual representable limits, use Massimiliano's approach instead. – luiscubal Jan 31 '14 at 2:17

To check if the fundamental type int is 32 bits wide I would do the following:

#include<limits>
#include<cstdint>

static_assert( std::numeric_limits<int>::max() == std::numeric_limits<int32_t>::max() , "int is not 32 bits wide");


which should be (to the best of my understanding) safer than what is proposed by @luiscubal.

The point I would raise with the accepted answer is that not all the bits in the object representation of an int may be used to represent a numeric value.

In fact, even though in the C++ standard (section 3.9) the issue is not clearly stated as in the C standard (section 6.2.6.2), I think the possibility of having padding bits in an integer type representation is allowed for compatibility reasons.