SAS Loops – Understanding Leave and Continue

The SAS language sometimes appears ambiguous to programmers with experience in other languages because it doesn’t support statements like “break” and “continue.” 

In SAS, the LEAVE statement is equivalent to the “break” statement. It provides a way to exit an iterative loop immediately. Using CONTINUE statements, SAS DATA skips over any remaining loop statements and starts the next iteration.

SAS Loops – Understanding Leave and Continue

The LEAVE statement

The Leave statement stops processing the current loop and begins processing the next statement in the sequence.

data _null_;
   do i= 1 to 10;
      if i = 5 then leave;
      put i=;
   end;
 ;
 put 'Loop Over';
run;

Results:

i=1
 i=2
 i=3
 i=4
 Loop Over

In the above example, even though the loop is till 10, it will exit when i=5 because of the Leave statement.

The Continue Statement

When the CONTINUE statement is used, the DATA step skips the remaining body of the loop and moves on to the next iteration. The condition is used to skip processing when it is true.

data _null_;
   do i= 1 to 10;
      if i = 5 then continue;
      put i=;
   end;
 ;
 put 'Loop Over';
run;

Results:

i=1
 i=2
 i=3
 i=4
 i=6
 i=7
 i=8
 i=9
 i=10
 Loop Over

We have a similar example, with the only difference of adding the continue statement. The SAS statement if i = 5 then continue; means if the value of i=5, then skip and move to the next iteration. You can see that i=5 has been skipped from the output.

Leave and Continue in SAS
Leave and Continue in SAS

The CONTINUE and the LEAVE statements are “jump statements” that tell the program the location of the next statement to execute. Using LEAVE and CONTINUE statements, SAS loops can be managed easily. In SAS, there is no need to code additional logic, such as the value of a counter variable, to determine what to do on the last iteration.

Every week we'll send you SAS tips and in-depth tutorials

JOIN OUR COMMUNITY OF SAS Programmers!

Subhro Kar is an Analyst with over five years of experience. As a programmer specializing in SAS (Statistical Analysis System), Subhro also offers tutorials and guides on how to approach the coding language. His website, 9to5sas, offers students and new programmers useful easy-to-grasp resources to help them understand the fundamentals of SAS. Through this website, he shares his passion for programming while giving back to up-and-coming programmers in the field. Subhro’s mission is to offer quality tips, tricks, and lessons that give SAS beginners the skills they need to succeed.