-1

I saw some code looking like this:

Object *area = new Object[n];
memset(area, 0xff, sizeof(Object) * count);

So this fills the Object array's every field with bit 1. Then later there are multiple places checking if an object's field has not been filled yet by checking against ~0 (negative zero):

const unsigned int NULL_INDEX = ~0;
...
if(object.field == NULL_INDEX) {...}

The field on that Object class is unsigned int type. I'm confused that why 0xff can be evaluated to be equal to ~0, on unsigned int? I saw another post talking about 0xff equals -1 on 2's complement system, and found another post which I think it means that whether a C++ program interprets 0xff to be -1 or ~0 is system dependent?

What exactly is the portable way in C++ to check for integer when filled with 0xff? Should this be checked against unsigned int or signed int? I'm so confused...

Community
  • 1
  • 1
Superziyi
  • 609
  • 1
  • 9
  • 30
  • 10
    `~0` is not negative 0. – Sam Varshavchik Jan 21 '17 at 01:42
  • ~ invert every bit. – Phil1970 Jan 21 '17 at 01:45
  • 1
    There are no negative 0 for integers in most common representation (2's complement). – Phil1970 Jan 21 '17 at 01:45
  • 1
    You should avoid using `memset` in C++. Using 0xFF could be problematic if `Object` holds pointers for example. `Object` constructor should be responsible for its own initialization. Objects should always be initialized when created so it would be pointless to check if they are initialized. If initialization cannot be completed, then an exception should be thrown. I would recommend you to read books like `Exceptional C++` from Sutter. – Phil1970 Jan 21 '17 at 01:49
  • @Phil1970 I know but I just wanted to understand what the existing code does. – Superziyi Jan 21 '17 at 02:12
  • @Phil1970 but there's negative 0 for 1's complement – Superziyi Jan 21 '17 at 02:17
  • Hmm now that my question answered...due to my own misunderstanding of the sign. Should this question be deleted or retained? I still would want to give credit to all people help me point it out and to the answerer, but I don't want the title to be misleading in google search results... – Superziyi Jan 21 '17 at 02:24

1 Answers1

3
~0

Just sets all the bits to 1. For example, if you have 32bit int and you use

int all_the_ones = ~0;

then you'd get 11111111111111111111111111111111 in the part of memory containing the value of all_the_ones

0xff sets 8 bits to 1, so for a 32bit int it would be 00000000000000000000000011111111

Anyway, for 0xff to be equal to ~0 on an int, the int in question would need to be 8bit/1byte, aka char

unsigned char a = ~0;
signed char b = ~0;

Would give a equal to 255 and b equal to -1

In memory they're both 11111111

I don't understand why you'd want to know if 0xff was stored in an int, but comparing against a or b above should work.

ScegfOd
  • 402
  • 3
  • 12