Search code examples
ccode-readability

Suggestions for improving the readability of this code


I am not sure whether I should ask this here or to some other StackExchange site, but I will go on... Please migrate if it is not suitable here)

I am reviewing a code. Requirement is to call a function nnumber of times with argument ranging from 0 to n. But if nis greater than 7, call the function only 7 times.

My colleague implemented it as follows:

void ExecuteFunctions(U8 count)
{
    if(count > 0) oprA(0);
    if(count > 1) oprA(1);
    if(count > 2) oprA(2);
    if(count > 3) oprA(3);
    if(count > 4) oprA(4);
    if(count > 5) oprA(5);
    if(count > 6) oprA(6);
    if(count > 7) oprA(7);
}

I modified it to:

void ExecuteFunctions(U8 count)
{
    for(U8 loopcnt = 0; loopcnt < count; loopcnt++)
    {
        oprA(loopcnt);

        if(loopcnt == 7)
        {
            // We don't want to execute this function more number of times if it is already executed 7 times
            break;
        }
    }
}

But I still feel that there could be a better way and need your inputs. (Also please migrate if it is off topic here)


Solution

  • MIN is a macro useful and often defined

    #define MIN(a,b)     (((a) > (b)) ? (b) : (a))
    #define MAX_STEP 7
    
    void ExecuteFunctions(U8 count)
    {
        int loopcnt = 0;
        count = MIN(count, MAX_STEP);
    
        while(loopcnt++ < count) {
            oprA(loopcnt);   
        }
    }