5
votes

I know there exists the LEAVE statement for data step DO loops to terminate the current loop. I cannot find, however, documentation for a corresponding macro command.

I've tried %LEAVE but that appears not to be defined.

  1. Does SAS not have a break statement for macro loops?
  2. If not, are there other options beside using %GOTO or a DATA _NULL_?
3
If you want more useful advice, post a simple example of your macro and why you want to %leave; the best way to do it depends on the specifics of your macro.Joe
data step LEAVE is just GOTO with implied LABEL. %GOTO is an acceptable alternative.data _null_

3 Answers

5
votes

I generally use a %GOTO for breaking out of a macro loop, if a %RETURN statement is not an option. And I sometimes also use a GOTO for leaving a datastep loop, because: the most CPU-efficient way of programming depends on being able to leave not just the current loop, but the loop surrounding that as well.

Until you can specify the level of loop that you want to break out of, there is no way around the occasional GOTO if you want to program with maximal efficiency and clarity. And this is true for SAS, C, C++ and any other language that uses loop constructs. Without GOTO you will have to do silly stuff like repeating code and checking for the same condition more than once.

4
votes

If you want to break out of a macro completely, you can use %abort (if you want to trigger an error) or %return (if you don't). These won't help if you just want to break out of a loop and carry on with the rest of your macro, but you could potentially write a loop as a separate macro and call it inside a larger macro.

Another option is to use %do %while or %do %until and check your exit condition at the start of each loop, with extra %if-%then-%do-%end blocks based on the same condition within the loop if you want to skip the rest of an iteration after a break condition is met halfway through.

2
votes

No, unfortunately there is no equivalent of leave in the macro language (as of v9.4).

You can see a complete list of macro statements in the documentation in the Macro Language Dictionary.

As a workaround you will have to manually trigger an exit condition for your loop.