#include<stdio.h>
int main()
{
printf("%c\n",~('C'*-1));
return 0;
}
I have tried the above source code and executed without any warnings.
The output is B. I am excited how the above code is processed and what is the meaning for printf("%c\n",~('C'*-1))
In C, 'C'
is an int
, it's a small integer with a value of 67
(assuming ASCII). You can get each step from:
#include<stdio.h>
int main()
{
printf("%d\n", 'C'); //67
printf("%d\n", 'C' * -1); //-67
printf("%d\n", ~('C' * - 1)); //66
printf("%c\n",~('C' * -1)); //B
return 0;
}
In 2's complement, the value of ~(-67)
is 66
.
The only important part is this expression:
~('C' * -1)
Let's break it down:
'C'
is ASCII code 67.('C' * -1)
is -67.~
), and you have 01000010, which is 66.More generally, most computers use "two's complement" arithmetic, where numerical negation followed by bitwise negation is equivalent to subtracting 1. And of course B
is one less than C
in ASCII.
On a computer that doesn't use two's complement arithmetic, the result may be different. Such computers are rare.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With