1

Assume that the size of char is 1 byte and negatives are stored in 2's complement form

#include<stdio.h>
int main()
{
    char c = 125;
    c = c+10;
    printf("%d", c);
    return 0;
}

How can be the answer is -121?

Vistanza
  • 65
  • 10
  • Try writing 125, 135, and -121 on paper as 8-bit binary values. It should be very clear what's happening. Do you know what 2's complement means? – Pete Baughman Jun 04 '15 at 21:10
  • See: http://stackoverflow.com/questions/2054939/is-char-signed-or-unsigned-by-default and: http://en.wikipedia.org/wiki/Integer_overflow – NathanOliver Jun 04 '15 at 21:12

1 Answers1

3

125 + 10 = 135. This is above 127, hence the addition overflows and the end result is 135 - 256 = - 121.

Matthieu Moy
  • 15,151
  • 5
  • 38
  • 65
  • 3
    What is the significance of the number `127` for chars? – John Odom Jun 04 '15 at 21:12
  • 4
    @JohnOdom its 2^7 - 1. since one bit is used for the sign 127 is the max a singed char can represent. – NathanOliver Jun 04 '15 at 21:14
  • 3
    @NathanOliver John Odom is maybe being kind of pedantic but the point he's making is technically correct (The best kind of correct). Nothing forces a char to be an 8-bit value. – Pete Baughman Jun 04 '15 at 21:15
  • 1
    @PeteBaughman Nathan doesn't say that it's _forced_ to be an 8 bit value. Just that it _is_. John may be thinking of other languages, such as Java or C#. – Mr Lister Jun 04 '15 at 21:33
  • @MrLister: I believe it would be different platforms. Different platforms can have different `char` bits. The CDC Cyber uses a 6/12 bit scheme, 6 bits for popular things, 12 bits for extended. – Thomas Matthews Jun 04 '15 at 22:38