Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Ternary operator
#9
(10-31-2023, 01:13 AM)DSMan195276 Wrote:
(10-30-2023, 11:50 PM)Kernelpanic Wrote: Again: Can something like this be implemented in a function in QB64?
Not in the way it behaves in languages like C and Java, it would have to be built into the language to work properly. Ex. In C and Java you can do stuff like this:

Code: (Select All)
x = (a != 0)? 20 / a: 0; // Checks that a is not zero before dividing by it
There's no way to implement that correctly with a function. The `20 / a` in the ternary operator is only supposed to be evaluated if `a != 0` is true, but with functions all the arguments are evaluated before the function is called.
Yes, that obviously does not work. How should such and similar variations be intercepted?
Gets kind of complicated.

Code: (Select All)

'Tenaerer Operator , Problem in Funktion - 31. okt 2023
'x = (a != 0)? 20 / a: 0; // Checks that a is not zero before dividing by it

Option _Explicit

Declare Function tenaererOperator(a As Double, b As Double) As Doeble

Dim As Double a, b, x

Locate 3, 3
Input "Zahl a: ", a

Locate 4, 3
Input "Zahl b: ", b

If a <> 0 Then
  x = b / a
Else
  x = 0
End If

Locate 7, 3
Print Using "b / a = ##.####"; x

Locate 9, 3
If tenaererOperator(a, b) = -1 Then
  Print "Keine negativen Werte!"
ElseIf tenaererOperator(a, b) = -2 Then
  Print "Division durch Null!"
Else
  Print Using "x = ###.####"; tenaererOperator(a, b)
End If

End

Function tenaererOperator (a As Double, b As Double)

  Dim As Double x

  If a <> 0 And Sgn(a) = 1 And Sgn(b) = 1 Then
    x = b / a
  ElseIf a <> 0 And Sgn(a) = -1 Then
    x = -1
  ElseIf a <> 0 And b = 0 Then
    x = -2
  Else
    x = 0
  End If

  tenaererOperator = x
End Function
Reply


Messages In This Thread
Ternary operator - by Kernelpanic - 10-30-2023, 09:57 PM
RE: Ternary operator - by DSMan195276 - 10-30-2023, 10:45 PM
RE: Ternary operator - by bplus - 10-30-2023, 11:08 PM
RE: Ternary operator - by Kernelpanic - 10-30-2023, 11:50 PM
RE: Ternary operator - by DSMan195276 - 10-31-2023, 01:13 AM
RE: Ternary operator - by Kernelpanic - 10-31-2023, 03:36 PM
RE: Ternary operator - by bplus - 10-31-2023, 01:37 AM
RE: Ternary operator - by DSMan195276 - 10-31-2023, 01:49 AM
RE: Ternary operator - by bplus - 10-31-2023, 02:02 AM



Users browsing this thread: 1 Guest(s)