Home > Mobile >  C how can I simplify this if else statement?
C how can I simplify this if else statement?

Time:08-10

I would like to know how I could simplify a statement like the one below.

I have similar code everywhere, and would like to clear it up.

if(isActive)
{
    if(columnId == 4)
        g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
}
else
{
    if(columnId == 4)
        g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

isActive, as you can imagine, is a bool value.

CodePudding user response:

At first glance, it's most apparent that this code only does anything if columnId == 4.

if(columnId == 4)
{
    if(isActive)
    {
        g.drawText(active[row].value, 2, 0, width, height, Justification::centredLeft, true);
    }
    else
    {
        g.drawText(inactive[row].value, 2, 0, width, height, Justification::centredLeft, true);
    }
}

At second glance, those two bulky lines are almost the same.

if(columnId == 4)
{
    auto & text = isActive ? active : inactive;
    g.drawText(text[row].value, 2, 0, width, height, Justification::centredLeft, true);
}

CodePudding user response:

if (columnId != 4)
    ; // do nothing
else if (isActive)
    . . .
else
    . . .
  • Related