options mlogic symbolgen mprint
%macro calc(a=,b=,op=);
%global c;
%if %str(&op.)=%nrstr(+) %then
%let C=%eval(&a.+ &b.);
%if %str(&op.)=%nrstr(-) %then
%let C=%eval(&a. - &b.);
%if %str(&op.)= %nrstr(*) %then
%let C=%eval(&a.* &b.);
%if %str(&op.)=%nrstr(/) %then %do;
%if &b.=0 %then
%put "SOORRY";
%else
%let C=%eval(&a./ &b.);
%end;
%mend;
Hi @ANIRBAN2,
Thanks for sharing the code and error. There are a few things to note with the macro definition, but for starters, how are you calling the macro? Have you tried something like the following?
%calc(a=1,b=2,op=%str(+));
Kind regards,
Amir.
Hi @ANIRBAN2,
Thanks for sharing the code and error. There are a few things to note with the macro definition, but for starters, how are you calling the macro? Have you tried something like the following?
%calc(a=1,b=2,op=%str(+));
Kind regards,
Amir.
Is this just an experiment to see if you can do arithmetic in SAS macro language or is it for some other purpose?
A SAS DATA step is a much better place to do calculations like this and it can still be inside a macro:
options mlogic symbolgen mprint
%macro calc(a=,b=,op=);
%global c;
data _null_;
&c = &a &op &b;
run;
%mend;
Numeric operators within a %IF condition cause trouble. The macro processor will look to perform math. Instead of using quoting functions, simply use double quotes so macro language knows you have characters and won't try to perform math:
%if "&op" = "+" %then
%let C=%eval(&a.+ &b.);
Be sure to use double quotes (not single quotes), and make certain that the value of &OP does not contain any leading or trailing blanks.
The reason that the %if statement causes trouble when dealing with character values is that an implicit call to the %Eval Macro Function is performed behind the scenes. As the %Eval Doc says, it "Evaluates arithmetic and logical expressions using integer arithmetic."
This can cause various problems. For example, if a values has a dot in it as below. Here, the macro m will conclude that 10.0 is less than 2.0.
%macro m;
%if 10.0 > 2.0 %then %do;
%put 10.0 is greater than 2.0!;
%end;
%else %do;
%put 10.0 is less than 2.0!;
%end;
%mend;
%m;
I doubt that you actually really need this macro. However, for a workaround, I would go with @Astoundings solution.
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!
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.
Ready to level-up your skills? Choose your own adventure.