+ 1
C operators......can anyone tell me how this code works?
Operator and precedance. https://code.sololearn.com/cZ0F652fll8Y/?ref=app
3 Respostas
+ 2
Ok, let’s break this down.
!b, b is 5 and is considered a positive-boolean value. Doing a logical NOT (!) flips this to a false value: !b = !5 = 0
Next, ~!b or now ~0
~ is a bitwise NOT operator. Here is an article that highlights how bitwise operators differ from logical operators https://www.geeksforgeeks.org/what-are-the-differences-between-bitwise-and-logical-and-operators-in-cc/ Here is a stackoverflow thread briefly covering that the bitwise NOT operator flips all the bits in a binary number https://stackoverflow.com/questions/7207391/the-tilde-operator-in-c e.g 101 becomes 010
So we are going to flip the bits of 0 to calculate ~0.
The marked answer in this thread here https://stackoverflow.com/questions/13147790/tilde-c-unsigned-vs-signed-integer points out that signed integers are represented using two’s complement: there will be a bit, the leftmost bit, that indicates the sign/positivity or negativity of the value. 0xxxxx... for positive, 1xxxxx... for negative. There are examples here https://en.m.wikipedia.org/wiki/Two%27s_complement
By default, ints are signed unless declared otherwise. Using this online converter https://www.exploringbinary.com/twos-complement-converter/ I can see that
0 is 00000000 (keeping default of 8 bits)
So flipping this gives
11111111
The leftmost bit being a 1 already tells me this will be a negative value: using the converter shows me this is the decimal value of -1
This leaves the last part of
~!b + b == c
We have calculated that ~!b = ~0 = -1
b == c is true, i.e. 1
Therefore -1 + 1 = 0
+ 1
That’s ok :)
0
Thank you..!