Macro/Literal Expressions
Posted: Tue Jul 31, 2018 7:52 pm
I often use macro expressions like the following in my code:
I can see that the preprocessor correctly expands this to:
Is the Basic compiler smart enough to optimize`16*3/4` to `12`, or will the expression be evaluated at runtime?
Also, how does the compiler handle the following examples, where variables and literal expressions are mixed?
Optimization of expressions A and C seems natural due to order of operations/evaluation order. Similarly, expression B cannot be optimized, because though algebraically equal, integer division would yield a different result.
Expressions D and E are less obvious. Though optimization would change the order in which the expression is evaluated, the result should be the same, unless integer overflow occurs. This would also be more difficult for the compiler to detect, as these situations often cannot be identified by syntax alone.
Edit:
What if I use `CONST` instead of `#define` in the first example? As in:
Code: Select all
#define LENGTH 16
if idx > LENGTH*3/4 then print "Almost full"
Code: Select all
if idx > 16*3/4 then print "Almost full"
Also, how does the compiler handle the following examples, where variables and literal expressions are mixed?
Code: Select all
dim a as integer
a = 3
' I would expect these expressions to be evaluated in the following ways:
print a*(5/2) ' => a*(2) [6] (A)
print a*5/2 ' => a*5/2 [7] (B)
print 5*2*a ' => (10)*a [30] (C)
print a*5*2 ' =? a*(10) [30] (D)
print a*6/2 ' =? a*(3) [9] (E)
Expressions D and E are less obvious. Though optimization would change the order in which the expression is evaluated, the result should be the same, unless integer overflow occurs. This would also be more difficult for the compiler to detect, as these situations often cannot be identified by syntax alone.
Edit:
What if I use `CONST` instead of `#define` in the first example? As in:
Code: Select all
CONST LENGTH = 16
if idx > LENGTH*3/4 then print "Almost full"