+14  A: 

This may not be the most elegant method, but one thing that you may be able to leverage is UINT_MAX defined in "limits.h". That is, ...

if UINT_MAX == 65535, then you would know that sizeof (unsigned) = 2

if UINT_MAX == 4294967295, then you would know that sizeof (unsigned) = 4.

and so on.

As I said, not elegant, but it should provide some level of usability.

Hope this helps.

Sparky
This is a valid answer that is not in the "duplicate" question. So, I've voted to reopen.
Judge Maygarden
The preprocessor should be able to do some math, something like `#if UINT_MAX >> 8 == 0 // 1 byte` ... `#elif UINT_MAX >> 16 == 0 //two bytes` etc?
UncleBens
Technically the size of the integer could be bigger than this technique predicts, since `unsigned` is allowed to have padding bits, or smaller since CHAR_BIT need not be 8. So for correctness it might be worth also asserting somewhere (in a test, perhaps), that `sizeof` does give the size expected. In practice you can say with high confidence that it isn't gonna happen.
Steve Jessop
+1, `@Sparky` toward your first silver badge!
Matthieu M.
Thanks, I added an answer just to get around the need for explicitly plugging in values.
myahya
If `UCHAR_MAX == UINT_MAX` then `sizeof(1U)` _probably_ is one. But it still may be 3.
MSalters
+4  A: 

Based on Sparky's answer, here is a way that I would look a bit nicer (by eliminating the explicit numbers)

#include <limits.h>
#include <stdint.h>

//Check if size if 4bytes
#if UINT_MAX == UINT32_MAX

....

#endif

<limits.h> defines INT_MAX and <stdint.h> defines UINT32_MAX. Generally, <stdint.h> gives integer types with specified widths.

myahya
This works under gcc, under g++ it can be problematic. Sparky's solution is more general
myahya