0

What is the use of ~ in the following program

#include <stdio.h> char agentName(char partner) { return ~(partner*-1); } int main() { printf ("%c",agentName('K')); return 0; }

26th Jun 2020, 4:12 PM
Yash Chaudhari
Yash Chaudhari - avatar
2 Answers
+ 3
It simply makes the code obfuscated. Lots of folks here think such cuteness probably suitable for challenging learners, however, they actually fail miserably to convey the true essence of programming and software development in general. The ~ (tilde) operator is from the family of bitwise operators which operates on integral types in their bit level. What it does is to negate a number by flipping all its 1's to 0's and vice-versa. That is one's complement of that number in base 2 representation*. As you have probably run the code, the program generates 'J' as its output. The letter 'K' has the integer representation of 75** (0100 1011) which first inside the `agentName` function gets multiplied by -1 and becomes -75 with the binary representation as (10110101) in two's complement***, then "bitwise not" operator takes effect on it and becomes (0100 1010) which in decimal is 74 and 74 is the numeric representation of the letter 'J'. ________ * https://en.wikipedia.org/wiki/Ones%27_complement ** http://www.asciitable.com/ *** https://en.wikipedia.org/wiki/Two%27s_complement 75 = (0100 1011), -75 = 1's to 0's and 0's to 1's except the rightmost 1 = (1011 0101)
26th Jun 2020, 5:25 PM
Babak
Babak - avatar
+ 1
It's the bitwise not operator https://www.sololearn.com/learn/4076/?ref=app Your code will get the ascii value of K, inverse it and return a new character according to the inversed value. Actually Burey's lesson explains a lot ^^
26th Jun 2020, 5:17 PM
Seniru
Seniru - avatar