|
|
| Author |
Message |
GTBecker
Joined: 18 Jan 2006
Posts: 457
Location: Cape Coral
|
|
Posted: 21 December 2009, 2:55 AM Post subject: Constant expressions |
|
|
Is an expression that will always yield a constant evaluated at run time or it is equivalent to a constant?
For example, is there a price for the following self-documenting expression?
|
|
| Back to top |
|
 |
dkinzer Site Admin
Joined: 03 Sep 2005
Posts: 2499
Location: Portland, OR
|
|
Posted: 21 December 2009, 3:19 AM Post subject: Re: Constant expressions |
|
|
| GTBecker wrote: | | Is an expression that will always yield a constant evaluated at run time or it is equivalent to a constant? | Unless you turn off optimization (which is on by default) the compiler will detect compile-time constant value expressions (including those involving ZBasic System Library functions) and substitute the constant value. Consider this simple example: | Code: | Dim b as Byte
Sub Main()
Select Case (b)
Case Asc("0")
Debug.Print "xx"
End Select
End Sub | For a VM target, the resulting code looks like this: | Code: | Sub Main()
Select Case (b)
0019 1d4001 PSHA_B 0x0140 (320)
001c 1a30 PSHI_B 0x30 (48)
001e a0 CMPEQ_B
001f 030300 BRA_T 0025
0022 010800 BRA 002d
Case Asc("0")
Debug.Print "xx"
0025 09027878 PSHI_S "xx"
0029 fe26 SCALL OUTSTR
002b fe27 SCALL OUTEOL
End Select
End Sub
002d 06 RET
| Given that the result of Asc("0") is the value &H30, you can see that the instructions at 001c and 001e compare that value to the selection expression.
In contrast, with optimization off the following code is produced: | Code: | Sub Main()
Select Case (b)
0019 1d4001 PSHA_B 0x0140 (320)
001c 090130 PSHI_S "0"
001f 1b0100 PSHI_W 0x0001 (1)
0022 fe1b SCALL STRASC
0024 a0 CMPEQ_B
0025 030300 BRA_T 002b
0028 010800 BRA 0033
Case Asc("0")
Debug.Print "xx"
002b 09027878 PSHI_S "xx"
002f fe26 SCALL OUTSTR
0031 fe27 SCALL OUTEOL
End Select
End Sub
0033 06 RET | Here you can see that the string "0" is pushed and the system call STRASC is invoked.
Even though the mnemonics of the VM instructions have not been published, I think that it is not too difficult to get the gist of the code. |
|
| Back to top |
|
 |
mikep
Joined: 24 Sep 2005
Posts: 765
Location: Austin, TX
|
|
Posted: 21 December 2009, 3:37 AM Post subject: |
|
|
It is worth noting that the ZBasic compiler can handle quite sophisticated expressions. If you are in doubt you can always declare a constant and see if the compiler complains. For example | Code: | | Private Const Expr1 as Byte = Asc("0") |
|
|
| Back to top |
|
 |
GTBecker
Joined: 18 Jan 2006
Posts: 457
Location: Cape Coral
|
|
| Back to top |
|
 |
|