Search code examples
c++loopsoptimizationcoding-style

pop objects out of a stack


Let's say I want to pop objects out of a stack and check their state, whether it's FUP (facing up) or not.

I want to keep doing this until I reach a point where the stack is empty OR an instance's state is not facing up; in this case I need to push this instance back and stop looping.

Here's one way of doing it:

bool isfup = true;

while(pop(stack, &ins) && isfup = ins->state == FUP)
{
    // continue removing elements from stack
}

if(isfup == false)
    push(stack, ins);

and here's how I do it:

while(pop(stack, &ins) && (ins->state == FUP || (push(stack, ins) && false)));
// while( A && ( B || ( C && false ) ) );

My question is, Should I stop writing code this kind of style and go for clarity? or should I keep it?


Solution

  • Put it in a function using the long and clear way, and then call the function in one quick line when you need it invoked. That is the one of the purposes of functions in procedural programming, after all! :-)