Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking the sizeof an integer type in the preprocessor

How can I check the size of an unsigned in the preprocessor under g++? sizeof is out of the question since it is not defined when during preprocessing.

like image 626
myahya Avatar asked Apr 06 '10 13:04

myahya


People also ask

Is sizeof a preprocessor?

The preprocessor doesn't understand the sizeof operator, so you can't use it in preprocessor directives (some compilers do support it as an extension, but it's not standard). What you need is a static assertion, but they were only added to the language in C11.

Where is sizeof define?

sizeof (type name); The sizeof operator yields an integer equal to the size of the specified object or type in bytes. (Strictly, sizeof produces an unsigned integer value whose type, size_t , is defined in the header <stddef.


2 Answers

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.

like image 163
Sparky Avatar answered Sep 24 '22 14:09

Sparky


Based on Sparky's answer, here is a way that 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.

like image 36
myahya Avatar answered Sep 21 '22 14:09

myahya