Reputation: 6083
I am not able to understand why it's output is ffff it should be 0000. Let say int take 2 byte ffff will stored in memory : 1111 1111 1111 1111
so after ~a value will become: 0000 0000 0000 0000. but out put coming ffff am I missing some general concept ?
#include <stdio.h>
void main()
{
unsigned int a = 0xffff;
~a;
printf("%x", a);
}
Output : ffff
Upvotes: 0
Views: 1612
Reputation: 106012
In the statement
~a;
~
operator NOT (complement) the value of a
and its value gets discarded (unlike the unary operator ++
and --
), i.e, ~a
does nothing to a
unless you assign it to a
a = ~a;
Upvotes: 0
Reputation: 10456
How about saving the value of the operation:
a = ~a;
You did perform the bitwise ~
operation, but you did not assign the returned value to any variable.
This operator returns a value, and does not modify variable itself.
Upvotes: 1
Reputation:
You have to assign the value back to the variable. You are just doing ~a. You are not assigning it back to a.
a = ~a;
will give you proper output.
Upvotes: 1
Reputation: 5166
you should do
a = ~a;
to assign the negated value to a.
or if you want to just print it, do
printf("%x", ~a);
Upvotes: 5
Reputation: 17131
The ~
operator does not change the variable in place, it returns the result of the change. So in order to perform a bitwise negation of a variable you need to assign it to itself:
a = ~a;
Upvotes: 2