0

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 :-)

2
  • What language ? (Please add a suitable tag.) And what have you tried so far ?
    – Paul R
    Apr 3, 2014 at 8:34
  • it didn't say. I guess C++. I didn't know what to tag it since I basically posted the question word for word. And I haven't tried much. I don't really understand how I could get the same task. I started off with while(p){.
    – Tommy Boi
    Apr 3, 2014 at 8:48

2 Answers 2

2
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.

0
0

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;
}
2
  • You have not got rid of the short-circuit evaluation, as you still have &&.
    – Paul R
    Apr 3, 2014 at 10:25
  • No, I have gotten rid of the reliance on the assumption it exists. The code will no longer break if short circuit evaluation is not used, which I believe was the point.
    – omgz0r
    Apr 3, 2014 at 19:24

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.