cunsignedones-complement

What's the difference between (size_t)-1 and ~0?


I've seen both (size_t)-1 and ~0 used to represent large numbers, or numbers with all their bits flipped.

Is there any difference between the two? If so, what is it?

I found this question: What is the difference between -1 and ~0, however it did not answer my question because I'm dealing with unsigned integers (such as size_t), as opposed to signed integers (such as int).


Solution

  • What's the difference between (size_t)-1 and ~0?

    Type and value differ.

    (size_t)-1 is the same value as SIZE_MAX and has a type of size_t.

    ~0 is often -1 and has the type of int.


    Assigning both of those to a size_t will result in SIZE_MAX.

    size_t a = (size_t)-1; 
    size_t b = ~0;
    

    In the 2nd case, -1 is assigned to a b and undergoes a conversion first, wrapping around the -1 to the maximum size_t value.