Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How printf("%c\n",~('C'*-1)) is computed in c?

Tags:

c

#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))

like image 443
Sowmya Ravichandran Avatar asked Dec 19 '22 07:12

Sowmya Ravichandran


2 Answers

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.

like image 88
Yu Hao Avatar answered Jan 08 '23 08:01

Yu Hao


The only important part is this expression:

~('C' * -1)

Let's break it down:

  • 'C' is ASCII code 67.
  • ('C' * -1) is -67.
  • -67 is, in binary, 10111101
  • Bitwise negate that (with ~), and you have 01000010, which is 66.
  • 66 is the ASCII code for 'B'.

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.

like image 29
John Zwinck Avatar answered Jan 08 '23 07:01

John Zwinck