BookmarkSubscribeRSS Feed
tomcookbdp
Calcite | Level 5

Hi,

 

I am relatively new to DS2 and have a question about the scope of global variable assignments. See the following program.

 

proc ds2; 
    data _null_; 
        declare int x;  /* global x in global scope */ 
        declare int y;  /* global y in global scope */ 
/*         retain x y; */
        
    method init();   
        declare int x;  /* local x in local scope */   
        x = 5;          /* local x assigned 5 */   
        y = 6;          /* global y assigned 6 */   
        put '0. in init() ' x= y=; 
    end; 

    method run();    
        put '1. in run()  ' x= y=;         
        x = 1;    
        put '2. in run()  ' x= y=; 
    end; 

    method term(); 
        put '3. in term()  ' x= y=;  
    end; 
    enddata; 
run; 
quit; 

Here is the log:

0. in init()  x=5 y=6
1. in run() x= y=6
2. in run() x=1 y=6
3. in term() x= y=

 Both x and y are global variables. Variable y is assigned a value of 6 in the init() method and this value is still present in the run() method, as I would expect. However, y no longer has the assigned value in the term() method. Why is this?

 

By the way, explicitly retaining y seems to solve the problem, but I don't understand why this is necessary. Can anyone explain?

2 REPLIES 2
ChrisLysholm
SAS Employee

The TERM() method automatically resets global variables to uninitialized values.

There are a few situations where this will not occur, pre-defined variables, such as _N_, accumulator variables used in sum statements, variables specified in a RETAIN statement and package variables will not automatically be reset to uninitialized values in the TERM() method.

 

 

tomcookbdp
Calcite | Level 5
Many thanks.

sas-innovate-2024.png

Don't miss out on SAS Innovate - Register now for the FREE Livestream!

Can't make it to Vegas? No problem! Watch our general sessions LIVE or on-demand starting April 17th. Hear from SAS execs, best-selling author Adam Grant, Hot Ones host Sean Evans, top tech journalist Kara Swisher, AI expert Cassie Kozyrkov, and the mind-blowing dance crew iLuminate! Plus, get access to over 20 breakout sessions.

 

Register now!

How to Concatenate Values

Learn how use the CAT functions in SAS to join values from multiple variables into a single value.

Find more tutorials on the SAS Users YouTube channel.

Click image to register for webinarClick image to register for webinar

Classroom Training Available!

Select SAS Training centers are offering in-person courses. View upcoming courses for:

View all other training opportunities.

Discussion stats
  • 2 replies
  • 493 views
  • 0 likes
  • 2 in conversation