Click here to Skip to main content
15,881,588 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
C
#include<stdio.h>
int main()
{
    char c = 255;
     c = c +10;
     printf("%d",c);
}


What I have tried:

Why this program give me result 9
Posted
Updated 3-Apr-22 22:34pm
v2
Comments
M Imran Ansari 4-Apr-22 3:09am    
You are storing into character and calculating arithmetic operation, which is calculating as per ASCII values. What is your expected output? You

T0 add to what CPallini said, in C a char value is an 8-bit quantity, so it can hold values from 00000000 binary to 11111111 binary inclusive, and no other. If you add one to a value that contains 11111111 binary, it "rolls over" to 00000000 binary.

Conventionally, C char values are signed, which means that the most significant bit of the value controls if it is positive or negative - a '1' in the "top bit" indicates a negative number: 01111111 binary is 127 in decimal, 10000000 binary is -128 in decimal, and 11111111 binary is -1 in decimal.

So if you start with a char containing 255 and add 10 to it, what you are actually doing is adding 10 to -1:
decimal             binary
x = 10 + (-1)       x = 00001010 + 11111111
x = 10 - 1          x = 00001001
             x = 9


Make sense now?
 
Share this answer
 
Variable c range is [-128..+127] hence 255 is out of range. In such a case the behaviour is 'implementation-defined'. In your program c is actually initialized with -1.
 
Share this answer
 
v2

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900