char overflow in c





1. Cyclic nature of unsigned char:

Consider following c program:
#include<stdio.h>
void main(){
    unsigned char c1=260;
    unsigned char c2=-6;
    printf("%d  %d",c1,c2);
}

Output: 4   250 (why?)
This situation is known as overflow of unsigned char.
    Range of unsigned char is 0 to 255. If we will assign a value greater than 255 then value of variable will be changed to a value if we will move clockwise direction as shown in the figure according to number. If number is less than 0 then we have to move in anti clockwise direction.



  
Short cut formula to find cyclic value:
If number is X where X is greater than 255 then
New value = X % 256
If number is Y where Y is less than 0 then
New value = 256 – (Y% 256)
 
2. Cyclic nature of signed
char:

#include<stdio.h>
int main(){
    signed char c1=130;
    signed char c2=-130;
    printf("%d  %d",c1,c2);
    return 0;
}
Output: -126   126 (why?)
This situation is known as overflow of signed char.
  Range of unsigned char is -128 to 127. If we will assign a value greater than 127 then value of variable will be changed to a value if we will move clockwise direction as shown in the figure according to number. If we will assign a number which is less than -128 then we have to move in anti clockwise direction.




Shortcut formula to find cyclic value:
If number is X where X is greater than 127 then
p = X % 256
if p <=127
New value = p
else
New value = p – 256
 If number is Y where Y is less than -128 then
 p = Y % 256
If p <= 127
New value = -p
else
New value = 256 -p 





Overflow of char data type in c programming
Overflow of int data type in c programming
Overflow of long int data type in c programming
Overflow of float data type in c programming
Overflow of enum data type in c programming
Data type tutorial home
C tutorial home.






5 comments:

Unknown said...

#include
int main()
{
signed char c=-128;
printf("%d ",c);
return 0;
}
what is the value of c?

Unknown said...

-128 :D

Unknown said...

char c = 250;
c+=8;
What is the value of c?

Unknown said...

250+8 is 258 so 3 more than 255.
If we move 3 more places it gives us the answer 2.

Vishwaksen said...

2