I am looking for a C++ function that returns the size of a type. For example :
#include <stdint.h>
int16_t my_var;
int32_t size_of_var;
// magical_function is what I'm looking for
// size_of_var should be equal to 16 because my_var is a int16_t
size_of_var = my_var.magical_function() ;
I know that size() exists to get the length of a string, so I guess there is a function indicating that too.
Moreover, I'm working with Clang library, so I can get a Type (http://clang.llvm.org/doxygen/classclang_1_1Type.html) but I currently have no idea to compare 2 types and to know the bigger between those two.
The sizeof() function in C is a built-in function that is used to calculate the size (in bytes)that a data type occupies in the computer's memory. A computer's memory is a collection of byte-addressable chunks.
You can use the sizeof operator to determine the size that a data type represents. For example: sizeof(int); The sizeof operator applied to a type name yields the amount of memory that can be used by an object of that type, including any internal or trailing padding.
In case you want 16 instead of 2 for int16_t
sizeof(my_var) * CHAR_BIT
sizeof
give you how many bytes, and CHAR_BIT
give you how many bits in a byte (normally 8)
Available syntaxes for the command (sizeof) are:
Both of them return std::size_t
.
Examples of types are int
, float
, double
, whereas expressions can evaluate the size of an object. For clarification purposes I'll add the following:
sizeof(int); // Return size of int type.
sizeof(float); // Return size of float type.
sizeof(double); // Return size of double type.
struct my_struct {}; // Creates an empty struct named my_struct.
my_struct alpha; // Initializes alpha as a my_struct.
sizeof alpha; // Returns size of alpha.
Further information can be found here.
Hope it helps!
To calculate the size of a type in bits, use the CHAR_BIT
macro in conjunction with the sizeof
operator:
#include <cstdint>
#include <climits>
int16_t my_var;
int32_t size_of_var;
// size_of_var should be equal to 16 because my_var is a int16_t
size_of_var = CHAR_BIT * sizeof(int16_t);
You may try like this:
size_of_var = sizeof(my_var);
In your case you may try with:
sizeof(my_var) * CHAR_BIT
On a side note:
C99 standard requires that
sizeof(short) <= sizeof(int) <= sizeof(long) < sizeof(long long)
Type C99 Minimum Windows 32bit
char 8 8
short 16 16
int 16 32
long 32 32
long long 64 64
Also int8_t
is guaranteed to be 8 bits, and int16_t
is guaranteed to be 16 bits, etc.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With