Zhro Zhro - 1 month ago 6x
C++ Question

How to calculate at runtime the maximum value allowed before datatype rollover?

I have the following structure:

struct Some_Struct {
uint32_t a;
int16_t b;
uint8_t c;

struct Other_Struct {
uint32_t a;
uint32_t b;
uint32_t c;

The variable size is being calculated as such:

uint32_t size = sizeof(Some_Struct) + sizeof(Other_Struct) * n;

My question is, given a
Some_Struct and Other_Struct whose actual size is dependent on the platform, architecture, and packing, how can I at runtime determine the maximum number of
allowed before
rolls over?


You can use numeric_limits:

uint32_t maximum_n = (std::numeric_limits<uint32_t>::max() - sizeof(Some_Struct))
                                / sizeof(Other_Struct);