1

I am trying to initialize a bitmap to all bits on. My idea was to initialize an array of the buffer size and then use memcpy; however:

#include <stdio.h>

#define SIZE 5

int main () {
  int i[SIZE] = { ~0 };
  for (int j = 0 ; j < SIZE ; j++) {
    printf("%d\n", i[j]);
  }
  return 0;
}

results in:

-1
0
0
0
0

my expectation was that I would see all -1. Why does this not work, and how can I accomplish my goal?

user129393192
  • 797
  • 1
  • 8

1 Answers1

2

This:

int i[SIZE] = { ~0 };

Explicitly initializes only the first element of the array to ~0. The rest are implicitly set to 0.

If you want all bits to be set, you need to use memset:

memset(i, ~0, sizeof i);
dbush
  • 205,898
  • 23
  • 218
  • 273
  • Thanks. Is this always guaranteed to work for `~0` on signed and unsigned types? I saw that [this post](https://stackoverflow.com/questions/7202411/why-does-memsetarr-1-sizeofarr-sizeofint-not-clear-an-integer-array-t) mentioned some prohibitiveness around `memset`. – user129393192 May 20 '23 at 18:03
  • 1
    On a 2's complement system -- and they all are these days -- yes. – ikegami May 20 '23 at 18:15
  • Can I ask why it wouldn't work on a non- 2's complement system? It seems like the `~0` is interpreted as `unsigned char`, so I'm not sure why it would make a difference? – user129393192 May 20 '23 at 18:16
  • @user129393192, See [here](https://gist.github.com/ikegami/f72bd6a67a25b4d71fc1a68b895da588) – ikegami May 20 '23 at 18:37
  • Got it. That's very strange. The `-0` explanation made it very clear. I never would have expected that. – user129393192 May 20 '23 at 18:49
  • Does this mean that all integers are interpreted initially as `int`? Is this a result of casting or just integrally how it is for numbers? @ikegami – user129393192 May 21 '23 at 19:10
  • Depends on what suffix they have `0` is an `int`, but `0u` is an `unsigned int`. `l` for `long`. `ll` for `long long`. `l` and `ll` can be paired with `u` for the `unsigned` variant. – ikegami May 21 '23 at 19:12
  • Is that simply because `0` can be held in an `int`, or is it integrally defined that way? – user129393192 May 21 '23 at 19:15
  • I replaced my comment above. The new one explains better. – ikegami May 21 '23 at 19:16
  • Understood. So something like `~0u` could work in a one’s complement or sign magnitude system then, assuming truncation in a cast from `unsigned int` to `unsigned char`. If that’s the case then that’s probably the most portable/safest strategy. – user129393192 May 21 '23 at 19:49