Help using Base SAS procedures

Retain statement initial value

Posts: 1

Retain statement initial value

I have question regarding initialization of retain statement:

If we do not provide any initial value to variable in retain statement then where it will initialize? during compile time or during execution? and to what value: missing or zero?

Regular Contributor
Posts: 180

Re: Retain statement initial value

Execution time - Missing

Super User
Posts: 5,081

Re: Retain statement initial value

The initialization of all variables, retained or not, takes place at compilation time.

Some variables get re-initialized to missing during the execution phase of the DATA step.  The RETAIN statement merely tells SAS to skip re-initializing the variable during the execution phase.

If the RETAIN statement does not supply an initial value, the initial value is missing.  However, note that a "sum" statement is related to the concept of RETAIN and initial values:

tot + 1;

This statement means that TOT will be retained, and will be given an initial value of zero during the compilation phase of the DATA step.

Posts: 45

Re: Retain statement initial value


I have two (2) follow up questions:

1) Can you give us an example of which variables get re-initialized during the execution phase? I thought execution is merely read and write (and calcuation if that applies).

2) What happens if you retain a variable with a valid value that is being read. For example, say variable x=2 in the first observation and I wrote a line of code as follows: retain x;. Doesn't that mean the value of 2 is retained in PDV during the initialization of the PDV in the second iteration of the DATA step?

Thanks in advance,


Super User
Posts: 5,081

Re: Retain statement initial value

For question 1, I think this is the complete list.  The DATA step retains (a) any variable mentioned in a RETAIN statement, (b) the first variable in a SUM statement, and (c) any variable that comes from a SAS data set (regardless of whether the SAS data set is being read with a SET, MERGE, or UPDATE statement).

For question 2, yes the variable is retained.  Your programming statements may overwrite that retained value, however.

To illustrate, you might try creating some variations on these programs:

data test1;

   put 'Before:  ' x=;

   input dummy;

   retain x;


   put 'After:  ' x=;





data _null_;

   put 'Before:  ' x=;

   set test1;

   x=_n_ + 10;

   put 'After:  ' x=;


Ask a Question
Discussion stats
  • 4 replies
  • 4 in conversation