Assignment Efficiency - Repetitive Assignment vs IF statement

2 days ago
12 hours ago
  • wayne-riesterer

    wayne-riesterer - 2 days ago

    Hello

    Can anyone see any problems with constant assignment as in the following statement:

    Coils[0] := Coils[0] OR (Buttons[0] AND Sensors[0] > 6);

    Rather than using the more verbose and vertically-larger:

    IF NOT Coils[0] AND Buttons[0] AND (Sensors[0] > 6) THEN
        Coils[0] := TRUE;
    END_IF
    

    Also, is the test expression short-circuited in the latter case? In other words, will the runtime move on after it sees Coils[0] = FALSE AND?

    Thanks

     
  • ojz0r - 2 days ago

    Its important that you know the difference between the two.

    Example 1:

    Coils[0] := Coils[0] OR (Buttons[0] AND Sensors[0] > 6);
    

    In this case the statements will be evaluated every scan and result in either true or false for Coils[0].

    Example 2:

    IF NOT Coils[0] AND Buttons[0] AND (Sensors[0] > 6) THEN
        Coils[0] := TRUE;
    END_IF
    

    In this example Coils[0] will latch the result in a true evaluation, if you want it to behave the same way as example 1 then you need to do it like example 3 below:

    IF NOT Coils[0] AND Buttons[0] AND (Sensors[0] > 6) THEN
        Coils[0] := TRUE;
    ELSE
        Coils[0] := FALSE;
    END_IF
    

    However back to the real question. There is no problem using either example 1 or example 3, if im not requiring a latch i usually go with example 1 as it is more compact.

     
    πŸ‘
    1
  • wayne-riesterer

    wayne-riesterer - 12 hours ago

    Thanks for your responses. I like to write the leanest possible code that I can because it makes it much easier to read/maintain/debug.

    OR_ELSE is what I was looking for. I wasn't sure if CodeSys short-circuited evaluation and I didn't realize this operator existed. Thanks!

     

Log in to post a comment.