top button
Flag Notify
    Connect to us
      Facebook Login
      Site Registration

Facebook Login
Site Registration

C: How the ans become -6, whether char val=200 is signed or unsigned?

+1 vote
713 views
#include <stdio.h>
int main()
{
  char val=250;
  int ans;
  ans= val+ !val + ~val + ++val;
  printf("%d",ans);
  return 0;
}
posted Oct 4, 2016 by anonymous

Share this question
Facebook Share Button Twitter Share Button LinkedIn Share Button

2 Answers

0 votes

If you don't specify unsigned before the data type then it will take signed by default.
So, in this case,

char val=250;

it is nothing but a signed character.

All the data type does have their range, range for the signed char is -128 to +127

Now, when you are trying to assign val as 250 (which is out of the range)

Binary representation of 250 is,
1111 1010

Now as you know, the first bit is considered as a signed bit so we have to take 1's complement of the same number and put minus before that (because of the signed bit)

1's complement of 250 is,
1111 1010 = 250
0000 0101 = 6

That's why even though you are assigning 250 to a signed char, it is taking -6.
And for the unsigned char value will be 250 itself because range of unsigned char is 0 to 255

answer Oct 5, 2016 by Chirag Gangdev
–1 vote

Char by default is signed so char 250 is nothing but -6.

To confirm just test the following code -

#include <stdio.h>

int main()
{
  char val=250;
  int ans;
  ans= val;
  printf("%d",ans);
  return 0;
}
answer Oct 4, 2016 by Salil Agrawal
Contact Us
+91 9880187415
sales@queryhome.net
support@queryhome.net
#280, 3rd floor, 5th Main
6th Sector, HSR Layout
Bangalore-560102
Karnataka INDIA.
QUERY HOME
...