Search code examples
c++sizeof

c++ sizeof - need help understanding


I am having trouble understanding a line of code. I see that an array is initialized as follows:

static const uint SmartBatteryWattHoursTable[1 << 4] = {
  0,  14,  27,  41,  54,  68,  86, 104,
120, 150, 180, 210, 240, 270, 300, 330};

However I can't tell what the following code means:

int x  = sizeof(SmartBatteryWattHoursTable) / sizeof(*SmartBatteryWattHoursTable));

I understand that the numerator will evaluate to 16 * 4 = 64. But what does the denominator evaluate to?


Solution

  • The code is declaring an array of 16 (1 << 4) uint values.

    The statement sizeof(SmartBatteryWattHoursTable) returns the byte size of the entire array, thus sizeof(uint) * 16 = 64 (assuming a 4-byte uint).

    An array decays into a pointer to the 1st element, thus *SmartBatteryWattHoursTable is the same as *(&SmartBatteryWattHoursTable[0]). So the statement sizeof(*SmartBatteryWattHoursTable) returns the byte size of the 1st element of the array, ie of a single uint, thus 4.

    Thus, x is set to 64 / 4 = 16, ie the number of elements in the array.

    This is a very common way to get the element size of a fixed array, prior to the addition of std::size() to the standard C++ library in C++17 (and std::ssize() in C++20).