Basic and Advance C Question:

How can I ensure that integer arithmetic doesnt overflow?

Tweet Share WhatsApp

Answer:

The usual approach is to test the operands against the limits in the header file <limits.h> before doing the operation. For example, here is a ``careful'' addition function:

int
chkadd(int a, int b)
{
if(INT_MAX - b < a) {
fputs("int overflown", stderr);
return INT_MAX;
}
return a + b;
}

Download C Programming PDF Read All 221 C Programming Questions
Previous QuestionNext Question
I am trying to compile this programHow can I handle floating-point exceptions gracefully?