Mohammed BRAHMI - 1 year ago 133

C Question

I want to initialize an int array with constant values, with all the 2^n values from 2^0 to 2^31 and I want to know which method below is right and if it gives the result I want and if there are easier or shorter methods to initialize it.

`static const char two_n[32];`

two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,

8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,

2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,

268435456, 536870912, 1073741824, 2147483648};

or

`static const char *two_n[32];`

two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,

8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,

2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,

268435456, 536870912, 1073741824, 2147483648};

or

`static const int two_n[32];`

two_n[32] = {1, 2 ,4 ,8, 16, 32, 64, 128, 256, 512, 1024, 2048, 4096,

8192, 16384, 32768, 65535, 131070, 262140, 524280, 1048560,

2097152, 4194304, 8388608, 16777216, 33554432, 67108864, 134217728,

268435456, 536870912, 1073741824, 2147483648};

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

Answer Source

Neither of the above because both the types of the arrays and the initializers are incorrect. Use `uint32_t`

or `unsigned long`

as these are guaranteed to be at least 32-bit wide and able to hold the value of 2^{31}, which might be beyond the range of `int`

:

```
static const unsigned long two_n[32] = {
1UL << 0, 1UL << 1, 1UL << 2, 1UL << 3,
1UL << 4, 1UL << 5, 1UL << 6, 1UL << 7,
1UL << 8, 1UL << 9, 1UL << 10, 1UL << 11,
1UL << 12, 1UL << 13, 1UL << 14, 1UL << 15,
1UL << 16, 1UL << 17, 1UL << 18, 1UL << 19,
1UL << 20, 1UL << 21, 1UL << 22, 1UL << 23,
1UL << 24, 1UL << 25, 1UL << 26, 1UL << 27,
1UL << 28, 1UL << 29, 1UL << 30, 1UL << 31
};
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**