balajimc55 balajimc55 - 1 month ago 9
C Question

c - optimizing repetitive if else

I have the following code:

if (a1 < a2)
a3=0;
else
a3=a1-a2;

if (b1 < b2)
b3=0;
else
b3=b1-b2;

if (c1 < c2)
c3=0;
else
c3=c1-c2;


The code is quite repetitive. Any suggestions on optimize code size? I do not want to use array.

usr usr
Answer

You can use a macro like:

#define COM(x,y) ((x<y)?0:(x-y))

...
a3 = COM(a1,a2);
b3 = COM(b1,b2);
c3 = COM(c1,c2);

or use a function instead.

int func(int x, int y)
{
   return (x<y)?0:(x-y);
}

a3 = func(a1,a2);
b3 = func(b1,b2);
c3 = func(c1,c2);

If you can use an array (for storing a, b, and c etc) for storing these values, then you can use a simple loop instead of repeating the macro/function call.