#include<stdio.h>
int main(void)
{
unsigned short a,e,f ; // 2 bytes data type
unsigned int temp1,temp2,temp4; // 4 bytes data type
unsigned long temp3; // 8 bytes data type
a=0xFFFF;
e=((a*a)+(a*a))/(2*a); // Line 8
//e=(((unsigned long)(a*a)+(unsigned long)(a*a)))/(unsigned int)(2*a);
temp1=a*a;
temp2=a*a;
temp3=(unsigned long)temp1+(unsigned long)temp2; // Line 14
temp4=2*a;
f=temp3/temp4;
printf("%u,%u,%lu,%u,%u,%u,%u\n",temp1,temp2,temp3,temp4,e,f,a);
return(1);
}
How do I fix the arithmetic (At Line 8 by appropriate typecasting of intermediate results) so that overflows are taken care of ? Currently it prints 65534 instead of expected 65535.
Why is the typecast necessary for Line 14 ?