Nested IF statements with multiple ELSE statements might require DO/END statements in IML


Nested IF statements with multiple ELSE statements might generate an error message even if the statements are syntactically correct. This error occurs only in "immediate mode," which means that PROC IML is executing statements in the main scope of the program. The problem can also occur in SAS/IML Studio if you are submitting statements in "statement mode."

For example, the following PROC IML statements generate an error:

proc iml;
  n=1; x=2; y=1;
  if n>0 then
     if x>y then w = x;
     else w = y;
  else w = 0;       
  print w;
quit;

Resulting SAS log

1 proc iml; NOTE: IML Ready 2 n=1; 2 ! x=2; 2 ! y=1; 3 if n>0 then 4 if x>y then w = x; 5 else w = y; 6 else w = 0; ERROR: ELSE does not follow IF statement at line=6 col=4. 7 print w; 8 quit; NOTE: Exiting IML.

This is a common problem known with many programming languages that is commonly referred to as a “Dangling Else/If-Else Ambiguity”.

When the SAS/IML parser encounters the first ELSE statement, the parser terminates the original IF statement regardless of nesting depth. Consequently, the second else no longer matches any pending IF statements and an error occurs.

DO/END statements can be used to direct the SAS/IML parser on how to interpret nested IF statements, as shown in the following example.

proc iml;
  n=1; x=2; y=1;
  if n>0 then do;
     if x>y then w = x;
     else w = y;
  end;
  else w = 0;       
  print w;
quit;

Another option for a workaround is to define a module like below:

proc iml;
  start test;
    n=1; x=2; y=1;
    if n>0 then
       if x>y then w = x;
       else w = y;
    else w = 0;       
    print w;
  finish;
  run test;
quit;