Reputation: 136
I would like to know what the ~ operand does with a char. Example code: the output is -1 if var="a".
int ret (char var)
{
int x;
x=var|~var;
return x;
}
int main()
{
printf("%d",ret("a"));
return 0;
}
I dont understand why it returns -1
Upvotes: 2
Views: 312
Reputation: 84569
The ~
operator is the negation
operator which has the identity -x-1
. There is both a logical (bitwise) negation and an arithmetic negation. C implements an arithmetic negation with the ~
. Take for example x=5
in binary:
x = 5
The the ~
operation would have the following effect:
~x = -5-1 = -6
In your case 'a'
is 97
or 01100001
, therefore
~a = -97-1 (or -98)
Sorry for the confusion
Upvotes: 1
Reputation: 6186
First "a"
and 'a'
are different. "a"
passes the address of string array "a"
and 'a'
passes the char a
. So you need to modify the code as
printf("%d",ret('a'));
Once modified, var
is 97
which is 0x00000061
and ~var
is -98
which is 0xffffff9e
.
0x00000061
| 0xffffff9e
will be 0xffffffff
that will be '-1' by Two's complement.
If you want 0xffffffff
, use %x
instead as
printf("0x%x",ret('a'));
Upvotes: 2