简体   繁体   中英

bit size of int array defined using typedef

typedef unsigned int Set[10];
Set set1;

I am correct in assuming that this creates a variable of type Set named set1 with 320 bits of storage space?

No. This creates a variable of type Set called set1 that has at least the amount of sequential storage on the C stack required for 10 unsigned int 's.

How many bits those are? This will depend on the platform and compiler. You can print how many bits it are in your particular setup by writing:

#include <limits.h>

typedef unsigned int Set[10];

int main(int argc, char **argv) {
    printf("Set has at least %d bits.\n", sizeof(Set) * CHAR_BIT);
    return 0;
}

The number of bits (and bytes 1 ) allocated may vary. Though, it is guaranteed to create a sequentiell storage for 10 integers which can be references through set1 .


What does the standard say?

The standard doesn't force a byte to contain N bits since that will make it harder to write compilers for a platform which doesn't have N bits in a byte .

[ open-std.org - n1147.pdf , 3.6/3]

  • A byte is composed of a contiguous sequence of bits, the number of which is implementation defined . The least significant bit is called the low-order bit; the most significant bit is called the high-order bit.

How would I get the number of bits in type T?

There is a constant ( CHAR_BIT ) defined that holds the number of bits in a char in < climits >.

Since all types consists of N bytes and a char is guaranteed to yield 1 when doing sizeof(char) we can use this constraint to calculate the bits in any arbitrary type.

#include <climits>

template<typename T>
struct sizeof_in_bits {
  enum {
    value = sizeof(T) * CHAR_BIT
  };
};

std::cerr << "output: " << sizeof_in_bits<unsigned int[10]>::value;

output: 320

The above output is, as mentioned, implementation-defined .


1 The standard doesn't force the size of an int to be M bytes. All it cleary states is that an int is to be able to hold at least -32767 through 32767 (if signed), and 0 to 65535 (if unsigned).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM