Sunday, April 21, 2013

AX X++ Break vs Continue actions

In AX X++, there are two keywords that are often confused between one another but do very different things: Break and Continue. Both have their own purpose independent of each other but often people forget. This is a little 101 tutorial.

Break - Breaks out of the loop completely. If there are 10 records to loop over, it will break skip all remaining iterations/records. This is nice when you don't have a need to process the remaining record.

Continue - Forces the next iteration of a loop. The continue statement causes the system to move straight to the next iteration/record of a 'for', 'while', or 'do...while' loop. For 'do' or 'while', the test is executed immediately.

More Info: MSDN: X++ Keywords [AX 2012]

static void daxLoopTest(Args _args)
{
    int i;

    info ("-----BREAK TEST - will attempt to loop 10 times but will hit break on 5");
    for (i=0; i<=10; i++)
    {
        info(strFmt("Loop #%1 - Before", i));

        if (i == 5)
        {
            info (strFmt("Break hit"));
            break;
        }
    }
    
    info ("-----CONTINUE TEST - on odd numbers, continue will be hit");
    for (i=0; i<=10; i++)
    {        
        if (i mod 2)
        {
            info ("Continue Hit");
            continue;   
        }
        
        info(strFmt("Loop #%1 - After", i));
    }
} 

Figure 1 - Infolog from the above code

2 comments: