Author Topic: Removal of C-style Ternary  (Read 939 times)

0 Members and 1 Guest are viewing this topic.

Charles Pegge

  • Guest
Removal of C-style Ternary
« on: August 22, 2020, 05:28:53 AM »
O2 will no longer support C expressions like:

r=(a>b ? c : d)

This is an expensive construction to check for during compilation.

Basic ternary expressions are easily implemented using a macro:

Code: [Select]
macro iif int(r, a ,b, c)
  if a
    r=b
  else
    r=c
  endif
end macro

r=iif(a>b , c, d)


correction: r=iif(a>b , c, d)
« Last Edit: September 14, 2020, 07:23:00 AM by Charles Pegge »

Nicola

  • Guest
Re: Removal of C-style Ternary
« Reply #1 on: September 14, 2020, 06:08:11 AM »
Please explain to me how this macro works?
thank you :-[

Charles Pegge

  • Guest
Re: Removal of C-style Ternary
« Reply #2 on: September 14, 2020, 07:20:18 AM »
Code: [Select]
macro iif int(r, a ,b, c)
'int indicates the type of temp variable r
'r will replace the macro invoked in an expression
'the macro is executed beforehand to resolve the value of r
'a is a boolean / comparative expression
'b and c are return values for r
  if a
    r=b
  else
    r=c
  endif
end macro

r=iif(a>b , c, d)

'expands to:

'int temp_r
'if a>b
'  temp_r=c
'else
' temp_r=d
'endif
'...
'r=temp_r

Nicola

  • Guest
Re: Removal of C-style Ternary
« Reply #3 on: September 18, 2020, 02:53:36 PM »
Ok Charles.
For me it is clearer in this way, using variables with different names, because I can better identify which are the variable parameters and which are part of the macro and which depend on the values ​​passed through the call of the macro itself. In our case iif ...
Still, a really good thing. Good job.

Code: OxygenBasic
  1. use console
  2. cls
  3.  
  4. 'macro iif int(r, a ,b, c)
  5. macro iif int(r, x ,y, z)
  6.   if x
  7.     r=y
  8.   else
  9.     r=z
  10.   endif
  11. end macro
  12.  
  13. '==main==========
  14. int a=5, b=6, c=7, d=9
  15.  
  16. int t=iif(a>b , c, d)
  17. print t
  18. wait

In this case, rightly so, the result is 9.

JRS

  • Guest
Re: Removal of C-style Ternary
« Reply #4 on: September 18, 2020, 03:33:37 PM »
Are macros like user defined syntax extensions?

How are macros unlike functions?

Code: Script BASIC
  1. 'IIF Function
  2.  
  3. FUNCTION IIF(x, y, z)
  4.   IF x THEN
  5.     IIF = y
  6.   ELSE
  7.     IIF = z
  8.   END IF
  9. END FUNCTION
  10.  
  11.  
  12. SPLIT "5,6,7,9" BY "," TO  a, b, c, d
  13.  
  14. PRINT IIF(a > b, c, d), "\n"
  15.  


C:\ScriptBASIC\examples>sbc iif.sb
9

C:\ScriptBASIC\examples>
« Last Edit: September 20, 2020, 06:31:09 PM by John »