#Function for variable expressions

3 messages · Page 1 of 1 (latest)

faint panther
#

I have multiple repeated sections of code that I'm confident I could make a single function but I haven't been able to come up with an elegant solution.

// Block 1
if (strcmp(filters.model, "NONE") != 0)
{
    filteredLineCount = 0;
    for (unsigned short i = 0; i <= lineCount; i++)
    {
        if (strstr(allCars[i].model, filters.model) != NULL)
        {
            filteredCars[filteredLineCount] = allCars[i];
            filteredLineCount++;
        }
    }
    filters.page = 0;
    for (unsigned short i = 0; i <= filteredLineCount; i++)
    {
        allCars[i] = filteredCars[i];
    }
    lineCount = filteredLineCount;
    filteredLineCount = 0;
}

// Block 2
if (filters.priceLowerBound != 0 && filters.priceUpperBound != 200000000)
{
    filteredLineCount = 0;
    for (unsigned short i = 0; i <= lineCount; i++)
    {
        if (allCars[i].price >= filters.priceLowerBound && allCars[i].price <= filters.priceUpperBound)
        {
            filteredCars[filteredLineCount] = allCars[i];
            filteredLineCount++;
        }
    }
    filters.page = 0;
    for (unsigned short i = 0; i <= filteredLineCount; i++)
    {
        allCars[i] = filteredCars[i];
    }
    lineCount = filteredLineCount;
    filteredLineCount = 0;
}

I have put 2 of the sections above, they are very similar but when I've tried to combine them it does very little to tidy up the code (Using more if statements/switches based on the iteration in a for loop).

Any help or pointers would be really appreciated 🙂

solid sandBOT
#

When your question is answered use !solved to mark the question as resolved.

Remember to ask specific questions, provide necessary details, and reduce your question to its simplest form. For tips on how to ask a good question use !howto ask.

paper quartz
#

You might not be able to put all of the repeated parts in functions but you can do with some, like this part :

filters.page = 0;
for (unsigned short i = 0; i <= filteredLineCount; i++)
{
    allCars[i] = filteredCars[i];
}
lineCount = filteredLineCount;
filteredLineCount = 0;