Areeb
Areeb

Reputation: 406

How does the OR expression in programming work

This weird question about OR gates popped up in my mind while in computer class, here's it:

When we add an OR gate to a conditional statement such that the condition specified first is true and the next is false, on executing the program does the compiler read both the conditions? or as soon as it hits to true it continues to the block of code below? This may be a completely stupid question but I'm curious.

Example:

if 1 < 2 or 3 != 3:
    <Do Sttuff>

In the above example does the compiler only check for 1 < 2 or does it check 3 != 3 too?

Upvotes: 0

Views: 54

Answers (2)

Bromind
Bromind

Reputation: 1138

you ask a question on the semantic of the language, so the answer is : it depends on how you define the semantic of your language.

In logic, we are generally (classic logic and intuitionist logic at least) not concerned about that : A or B <=> B or A, so they should give the same result, and we are not concerned on the computability.

When you want to implement a language, you can define your semantic as you want. Nowadays, most languages have a lazy evaluation, i.e. compute the minimum amount possible, i.e. as soon as we now the result, don't compute the remaining expression, but it is also possible that the definition of the language semantic do not precise that and so the effective computation is up to the compiler.

Upvotes: 0

nicomp
nicomp

Reputation: 4647

When you write

if 1 < 2 or 3 != 3:

The 1< 2 is true so the 3!= 3 never gets checked. The entire expression is considered true. It's called short-circuiting.

Don't confuse an OR gate, which is hardware, with an OR expression in software.

Upvotes: 1

Related Questions