Question

I have to rewrite this segment of code code that assumes short-circuit evaluation of Boolean expressions:

while ((p!=NULL) && (p->val != v)) p=p->next;

such that it performs exactly the same task without assuming the short-circuit evaluation of Boolean expressions. Can anyone help me out with this?

I've searched the internet but all I get is the differences between short-circuit eval and non short-circuit eval, but I can't find anything on rewriting one or the other to get them to do the same thing. It's for an exam review (not homework) so it would be great help someone solved it so I'd atleast know howto do this for simple code. Explanations welcome :-)

Was it helpful?

Solution

while(true)
{
    if (p == NULL)
        break;
    if (p->val == v)
        break;
    p = p->next;
}

Some explanation: the original code relies on short-circuit evaluation. p->val != v isn't evaluated if p!=NULL evaluates to false. If it would always evaluate the second expression, this might lead to an access violation. If you don't hva a short-circuiting && operator, you need to make sure in your code, p->val is only evaluated if p!=NULL.

OTHER TIPS

You simply need to split up the check for NULL and the accessing of a member of p into two statements.

Short circuit evaluation means that in an AND conditional, if the first operand is false, the code does not bother checking the second, as it already knows that the outcome is "false".

I'd say:

val = null;
while (p != null && val != v)
{
    p = p->next();
    val = p->val;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top