-1

Can Someone explain me what this line of code means

-(char)((unsigned char) ~0 >> 1) - 1);

I don't know why the writer used a " - " in front of char and the -1 in last. I know that the ~0 will turn all the bits to 1 and then right shift will shift it once so that a zero comes up in front.

  • 1
    Unary - negates. – stark Jul 17 '21 at 11:14
  • When you write `-3`, what does the `-` mean? – Karl Knechtel Jul 17 '21 at 11:29
  • 2
    That's horrible code. It's much simpler to get the minimum `char` value by looking at `CHAR_MIN` or `std::numeric_limits::min()`. – Pete Becker Jul 17 '21 at 11:58
  • @PeteBecker: It comes from a definition of `CHAR_MIN` or `SCHAR_MIN`. The question is an exploration of why `` defines values the way it does. If you read the question marked as an original and its answers, you will see that it is not horrible code and that the various components are useful in defining the constants generally. (As it turns out, the `char` cast is not needed for the `char` case, but it is needed in the cases generally, such as `long`.) – Eric Postpischil Jul 17 '21 at 12:33
  • 1
    @EricPostpischil -- the definition of `CHAR_MIN` is "minimum value for an object of type `char`". That code may well be from some standard library **implementation** of `CHAR_MIN`, but that doesn't make it good code. The standard library ships with a compiler, so it can rely on all sorts of non-portable hackery that works with that particular compiler. Most users should ignore details of how the standard library implements things. – Pete Becker Jul 17 '21 at 12:37
  • @PeteBecker: Yes **and that is what it does**. It is code in an **implementation** of ``, and the question marked as an original states that. The code was merely extracted from `` and put into a minimal program for study, not as an intent to use it in a deployed application. That is in fact practice we recommend on Stack Overflow, putting code into a [mre], and the other author posed the question correctly and cited its origin. The author here failed to cite the origin, but clearly the question arises in a similar manner; this code is not part of a deployed application. – Eric Postpischil Jul 17 '21 at 12:39
  • @EricPostpischil -- I stand by my statement. Most programmers (especially beginners) should not waste time studying hacker-head code like that. – Pete Becker Jul 17 '21 at 12:42

1 Answers1

0

it just negates (char)((unsigned char) ~0 >> 1) - 1).

you can see the difference live

Oblivion
  • 7,176
  • 2
  • 14
  • 33