Reputation: 374
I've seen several libraries and some C++ header files that provide compiler independent types but I don't understand quite why they are compiler independent.
For example:
int Number; // Not compiler Independent
typedef unsigned int U32;
U32 Number2; // Now this is compiler independent
Is this above true? If so, why? I don't quite understand why the usage of a typedef would mean that the size of Number2 is the same across compilers.
Upvotes: 0
Views: 422
Reputation: 110718
I'm assuming that you meant for the types to be the same with unsigned int Number
.
But no, these are exactly the same. Both declarations, Number
and Number2
, have the same type. Neither is more compiler independent than the other.
However, the point of using a typedef
like this is so that the developers of the library can easily change the integer type used by all functions that use U32
. If, for example, they are on a system that where an unsigned int
is not 32 bits, but an unsigned long
is, they could change the typedef
to:
typedef unsigned long U32;
In fact, it's possible to use the build system to conditionally change the typedef
depending on the target platform.
However, if you want a nice standardised way to ensure that the type is a 32 bit unsigned integer type, I recommend using std::uint32_t
from the <cstdint>
header. However, this type is not guaranteed to exist if you're on a machine with no 32 bit integer type. Instead, you can use std::uint_least32_t
, which will give you the smallest integer type with at least 32 bits.
Upvotes: 1
Reputation: 626
Elaborating on the comment,
Proposition : Use a typedef for compiler independence.
Rationale : Platform independence is a Good Thing
Implementation:
#ifdef _MSC_VER
#if _MSC_VER < 1400
typedef int bar;
#elif _MSC_VER < 1600
typedef char bar;
#else
typedef bool bar;
#else
#error "Unknown compiler"
#endif
The preprocessor macro chain is the important part not the typedef.
Disclaimer: I haven't compiled it!
Upvotes: 1
Reputation: 3345
As stated in the comments, the shown typedef is not compiler independent.
If you want a compiler independent way to get fixed sizes, you might want to use cstdint. This header file actually comes with your compiler and assures you a minimum size, but no maximum for bigger types (64 bit, 128 bit).
If you want to be completely sure about all the sizes of your types, you need to check it.
Upvotes: 0