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 2025: Register Now

Registration is now open for SAS Innovate 2025 , our biggest and most exciting global event of the year! Join us in Orlando, FL, May 6-9.
Sign up by Dec. 31 to get the 2024 rate of just $495.
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.

SAS Training: Just a Click Away

 Ready to level-up your skills? Choose your own adventure.

Browse our catalog!

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