A C compiler like that found in the Arduino IDE can short circuit?????? Read on….

What do you think the output of String g is at each stage??

String g = “no”;
int i = 10;

i > 10 && (g = “yes”);
Serial.println(g);

++i;
i > 10 && (g = “yes”);
Serial.println(g);

If you said:

no
yes

then you would be correct… but why??

In the case of logical AND function, A && B, if the first section ‘A’ is false, then there is no need to evaluate ‘B’ and anything AND’d with false is false…. no in our (i > 10) && (g = “yes”); scenario if i>10 evaluates to false, then it goes not try and evaluate g=”yes” as it know that it can only be false. This saves execution time and is part of the C compiler optimizing for time. This is know as short circuit behavior.

So its a neat way of saying

if(i>10) {
g = “yes”;
}

Would you use this in your code? any thoughts can be posted in the comments.

Can you think of any clever uses of such coding??

 

7 thoughts on “C Compiler Short Circuit”

  1. Your code uses `&` where you meant to use `&&`.

    Confusingly, it doesn’t do what you said, because `&` is just a plain bitwise And operator, not short-circuiting,

    As for “would you use this?”, short-circuiting is extremely useful, but hiding an assignment in the middle of an expression is a really bad idea for readability.

    1. Nice catch, I was trying to be all smart and “stuff”… 🙂

      I know it really works with && (logical) and had some brain fart thinking it would also work with & (arithmatic) … yeah… no.

      I stand corrected!

      Thanks!
      RichardS

    2. “As for “would you use this?”, short-circuiting is extremely useful, but hiding an assignment in the middle of an expression is a really bad idea for readability.”

      As for this comment, I concur. Readability is zero….

      Trying to come up with in my head some real funky use for it however, I always like these little “hidden tricks”

      RichardS

  2. I would not use the style shown here, but short circuiting is used every day in C / C++, e.g.

    “`if (obj && obj->field ==1) {

    “`

    You only want obj->field to be evaluated if obj is not NULL / 0.

  3. The line
    i > 10 && (g = “yes”)
    is a logical expression. C-compilers use to evaluate it from left to right. If the result of the first part, i.e. “i > 10”, is false, everything that follows “&&” will not change the result of it and the generated code will skip it. So “(g = “yes”)” is skipped in this line.
    The next time this line appears, the “I” has been incremented so the first part will be “true” and the assignment “(g = “yes”)” is executed.

    C is a very powerful language which makes it unforgiving.

Leave a Reply to Julian Nicholls Cancel reply

Your email address will not be published. Required fields are marked *

Captcha loading...