|Title||The use of macros with the power operator|
|Author||William Gould, StataCorp|
Be careful using macros with the power operator. Never code
... 'a'^2 ...
... ('a')^2 ...
In particular, macros will surprise you when they contain negative numbers.
. local a = -2 . display 'a'^2 −4
To understand why this occurred, remember that macros substitute and think about what the line looked like after substitution.
What do you think −22 should equal, 4 or −4? That depends on whether you take −22 to mean (−2)2 or −(22). Most people agree that −22 means −(22) and that the "right" answer is −4. Stata agrees with that:
. display -2^2 −4
You may agree that −22 = −4, but if a = −2, it is obvious that a2 should be 4 and that a2 should be 4 regardless of the sign of a. Stata agrees:
. input a a 1. -2 2. 2 3. end . generate b = a^2 . list +--------+ | a b | |--------| 1. | -2 4 | 2. | 2 4 | +--------+
The problem is that macros such as 'a' are not variables; they are substitutes. When you type "...'a'...", the contents of 'a' are picked up and dropped right in its place in what you typed.
If you type 'a'2 and 'a' contains −2, then the result is −22, which, as we previously agreed, is −4.
The programming rule I use is always to bind 'a' in parentheses — ('a') — when taking powers, and I do that whether 'a' is a macro or a scalar. With scalars it is unnecessary; scalars are variables and negative two is stored whole in it:
. scalar c = -2 . display c^2 4
but I bind my scalars in parentheses anyway because I sometimes forget whether 'a' is a macro or a scalar.
The danger of using 'a'2 rather than ('a')2 did not exist in Stata 4 and earlier; it does exist in all modern Statas.
Older Statas took −22 to be (−2)2 or 4, and so coding 'a'2 was perfectly safe. Interactive users, however, were shocked by this behavior, so we changed the way Stata works, and we made the change under version control so that old programs and ado-files continue to work:
. display -2^2 −4 . version 4.0 . display -2^2 4
As a programmer, I preferred Stata’s old way of working. That was, however, insufficient reason, because the old way made −22 produce 4, and that surprised interactive, nonprogramming users. The new way puts the confusing part back where it belongs, on programmers.