top | item 22946698

(no title)

xyzzy2020 | 5 years ago

How does this not break sizeof ?

discuss

order

tom_mellior|5 years ago

http://www.open-std.org/jtc1/sc22/wg14/www/docs/n2472.pdf: "_ExtInt types are bit-aligned to the next greatest power-of-2 up to 64 bits: the bit alignment A is min(64, next power-of-2(>=N)). The size of these types is the smallest multiple of the alignment greater than or equal to N. Formally, let M be the smallest integer such that A * M >= N. The size of these types for the purposes of layout and sizeof is the number of bits aligned to this calculated alignment, A * M. This permits the use of these types in allocated arrays using the common sizeof(Array)/sizeof(ElementType) pattern."

saagarjha|5 years ago

It’d probably round up to the nearest byte, as it already does with the boolean types.

wahern|5 years ago

The object size has to be at least the alignment size so that arrays work properly--&somearray[1] needs to be properly aligned, and that only works if the object size is a multiple of the alignment: sizeof myint >= _Alignof(myint) && (sizeof myint % _Alignof(myint)) == 0.

As the proposal says, the bit alignment of these types is min(64, next power-of-2(>=N)). (Of course, the alignment can't be smaller than 8 bits, which the proposal fails to account for.) Assuming CHAR_BIT==8, it follows that:

  sizeof _ExtInt(3) == 1   // 5 bits padding
  sizeof _ExtInt(17) == 4  // 15 bits padding
  sizeof _ExtInt(67) == 16 // 61 bits padding
So the amount of padding can be considerable. But that doesn't matter much. What they're trying to conserve is the number of value bits that need to be processed, and in particular minimize the number of logic gates required to process the value. Inside the FPGA presumably the value can be represented with exactly N bits, regardless of how many padding bits there are in external memory.

barbegal|5 years ago

Where does the spec say that it does that? As far as I can tell C only allows objects to have sizes in whole number of bytes, and that includes booleans.

Although a _Bool type can be used for a bit field (having size of 1 bit) but you can't use sizeof with a bit field.