logical operator precedence

:information_source: Attention Topic was automatically imported from the old Question2Answer platform.
:bust_in_silhouette: Asked By MrMonk
:warning: Old Version Published before Godot 3 was released.

what should the result be, for the code below ? thanks !
(edited: the result is True but it should be False, so I don’t understand why is so)

extends Node
var a = false
var b = false
var c = true
var d = true
var e = false

func _ready():
 if a or d or c and e :
	 print (true)
 else:
	 print(false)
 pass
:bust_in_silhouette: Reply From: Omicron

Check this : GDScript reference — Godot Engine (stable) documentation in English

Precedence of AND operator is higher than OR operator.

Anyway, without even checking docs, when coding, just use parenthesis if unsure.

:bust_in_silhouette: Reply From: Matt_UV

In binary operations, you can (basically) replace:
OR by + (addition)
AND by x (multiplication)
true by 1
false by 0
As in mathematics you always calculate multiplication before addition, you always check AND before OR

Which means:
a OR d OR c AND e could be written:
= a + d + c x e
= 0 + 1 + 1 x 0
= 0 + 1 + (1 x 0)
= 0 + 1 + 0
=1
= true

The correct result is True :wink:

As Omicron says: put parenthesis if you are unsure. That’s the best way of not making mistakes :wink:

Matt_UV | 2017-03-07 19:15