DATA Step, Macro, Functions and more

SAS global macro vs local macro

Reply
Contributor
Posts: 27

SAS global macro vs local macro

56. The following SAS program is submitted:
%let a=cat;
%macro animal(a=frog);
%let a=bird;
%mend;
%animal(a=pig)
%put a is &a;
Which one of the following is written to the SAS log?
(A) a is &a
(B) a is cat
(C) a is pig
(D) a is bird

The answer is B. But why (D) is not correct? Thanks a lot!
Super Contributor
Super Contributor
Posts: 366

Re: SAS global macro vs local macro

Posted in reply to richard_hu2003
Hello Richard_hu2003,

The question is related to global and local macrovariables relationship. In this case we have a global macro variable a with value 'cat', and inside the macro we have a local macrovariable a with value 'bird'. These are two different macro variables. Because macro does not change global macro variable its value remains unchanged and equals to 'cat'.

Sincerely,
SPR
Contributor
Posts: 27

Re: SAS global macro vs local macro

Got it! Thanks!
Valued Guide
Posts: 653

Re: SAS global macro vs local macro

Posted in reply to richard_hu2003
Richard_hu2003,

SPR is absolutly correct but the reason that there is a local and global version of &A is more subtle. A slight change in the program will give D as the answer.
[pre]%let a=cat;
%macro animal(b=frog);
%let a=bird;
%mend;
%animal(b=pig)
%put a is &a;
[/pre]

now there is no version of &A on the local table, and cat is replaced by bird.

In your original version of the macro %ANIMAL it is the parameter (A=) that forces a &A to appear on the local table. A %LET inside the macro is not sufficient. I feel that this is an important, albeit fairly subtle, difference in behavior that gets folks into trouble.
Contributor
Posts: 27

Re: SAS global macro vs local macro

Very helpful!! Thanks, ArtC.
Senior User
Posts: 1

Re: SAS global macro vs local macro

Posted in reply to richard_hu2003
Hi

I understand that first a global table with a= cat created and then a local table with a=frog created and in the last step it is updated to pig. But when resolving a macro variable (&a) doesn’t SAS first look into lical table and if it finds it it retrieves it from local (hence here pig) and if it cannot find it from local table it looks into global table?
Super User
Posts: 5,888

Re: SAS global macro vs local macro

Posted in reply to richard_hu2003
You are correct, but the question in the OP is based on resolving a macro variable in the global scope.
Data never sleeps
Ask a Question
Discussion stats
  • 6 replies
  • 2168 views
  • 1 like
  • 5 in conversation