SAS9

The Mysterious Array Error and Rule #1

Simon 12 vues

There is nothing more frustrating for a SAS© programmer than spending hours on a cryptic error message, only to realize that the problem was not with the complex logic, but with a simple missing character.

An instructive exchange on the user forum perfectly illustrates this scenario with the use of Arrays and DO blocks.

Note :
The Guilty Code
A user attempts to copy values from one array (ais) to another (trhead) under a condition, inside a loop.

Here is the submitted code:
1array region{22} region_1 - region_22;
2array ais{22} ais_1 - ais_22;
3array trhead{22} trhead1-trhead22;
4 
5DO i = 1 to dim(ais) ;
6 /* La ligne problématique */
7 IF region(i)='HEAD' THEN DO trhead(i)=ais(i); END;
8END;

The Deceptive Error

SAS© returns an error that seems to indicate a variable definition or type problem:

ERROR: The variable type of trhead is invalid in this context. ERROR: Illegal reference to the array trhead. ERROR 73-322: Expecting an =.

At first glance, one might think that the trhead array is improperly declared or that there is a type mismatch (numeric vs. character).

Note :
The Diagnosis: The THEN DO Trap
As quickly identified by the forum experts, the problem has nothing to do with the arrays. It's a classic punctuation error.

The DO statement is a standalone instruction. It must end with a semicolon.

The incorrect code: if region(i)='HEAD' then do trhead(i)=ais(i); SAS© interprets this as the start of an iterative loop (e.g., DO i = 1...), and doesn't understand why an array trhead(i) is being used as a loop counter.

The correction: You must add a semicolon right after the DO.
1IF region(i)='HEAD' THEN DO;
2trhead(i)=ais(i);
3END;
4 
Note :
The Golden Rule (Rule #1)
A user named David recalls in the discussion a fundamental rule taught to beginners but often forgotten by experts in the heat of the moment:

"Rule #1 of SAS© programming is: Where is the semicolon?"

Before looking for complex logic errors or rewriting your Array declarations, always check that whatever is between two semicolons constitutes a valid SAS© statement.

Formatting Tip
To avoid this specific error, it's recommended not to write the THEN DO and the following statement on the same line. Adopt the following indentation to make the error visually obvious:
1IF region(i)='HEAD' THEN DO;
2/* Le point-virgule est bien visible ici */
3trhead(i) = ais(i);
4 
5END;
6 

This type of syntax error is the one that wastes the most time ("I waste HOURS on!"). If SAS© insults you with "Variable Type" or "Expecting =" errors, start by taking a deep breath and looking for the missing semicolon.