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??

 

3 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

Leave a Reply

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

Captcha loading...