### Communities

tag:snake search within a tag
user:xxxx search by author id
score:0.5 posts with 0.5+ score
"snake oil" exact phrase
created:<1w created < 1 week ago
post_type:xxxx type of post
Q&A

Welcome to Software Development on Codidact!

Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.

# What is the meaning of "short circuit" operators?

+6
−0

When reading about various operators used by programming languages, the term "short circuit behavior" is often used. For example in this C code:

``````int a = 0;
a && b++
``````

Someone explained that `b++` is never executed because the logical AND operator "short circuits". What do they even mean with this?

Assuming I'm a layman at electronics (but not necessarily at programming), the association I get when hearing "short circuit" is something like connecting + directly to - on a battery, resulting in a spectacular failure such as cables burning up. And that doesn't seem like something I would want to happen to my program...

Why is it called "short circuit behavior"? What's the analogy and how is it helpful in understanding how certain operators work?

Why does this post require moderator attention?
Why should this post be closed?

Cables don't blow up from a short (5 comments)

+3
−0

It's an unfortunate analogy. Apart from being confusing, it does indeed assume some basic electronics knowledge. In electronics a short circuit (or the common jargon "a short") does not necessarily refer to a catastrophic event like cables burning up - it just means that you connect two signals/conductors with no resistance between them.

Whoever decided to use this term in the strange context of programming probably had something like this schematic in mind:

As we may recall from school, in case we have two resistors in parallel then the current flowing through the circuit is split between them. But in the above picture we have a conductor to the left bypassing R1 entirely. All the current flows through that conductor and zero current flows through R1. We may say that R1 is "short circuited" since both sides are connected to the same conductor.

This means that no matter what circuit or value we put in R1's place, zero current will pass through it. The analogy in programming is that in case we have `1 && b++`, then it doesn't matter what we write as the right operand because the program flow will only "pass" the left operand.

So supposedly we should compare the program counter in software with an electrical current. It is not really a helpful term at all even if you do know basic electronics.

As it turns out, it is probably better to use the formal programming terms. In the C language (and many others), this is referred to as order of evaluation. What that means in detail was explained here: What is the difference between operator precedence and order of evaluation?

Certain operators like the `&&` and `||` in C guarantee a left-to-right evaluation and also that the evaluation stops if it finds that the result cannot be true. `a && b++` is therefore 100% equivalent to this:

``````if(a)
{
if(b++)
{
do_stuff();
}
}
``````

The inner `if` will never get executed unless the outer `if` evaluates to true. Similarly, `a || b++` is 100% equivalent to

``````if(a)
{
do_stuff();
}
else if(b++)
{
do_stuff();
}
``````

But how can we know if a certain operator "short circuits"? Well if we have programming learning material of dubious quality, speaking of electrical terms, we can always abandon it and just peek directly into the C standard. C17 6.5.13 emphasis mine:

Logical AND operator
/--/
Unlike the bitwise binary `&` operator, the `&&` operator guarantees left-to-right evaluation; if the second operand is evaluated, there is a sequence point between the evaluations of the first and second operands. If the first operand compares equal to 0, the second operand is not evaluated.

These two bold sentences are what actually guarantees the "short circuit"-like behavior.

Most operators in C do not come with such a guarantee. But in higher level languages like Java, operators usually come with more guarantees by the standard and less ambiguous behavior, making Java safer and less bug-prone. The reason why C does not do that at the same extent is because C prioritizes performance over safety. An unspecified order of evaluation gives the compiler more freedom to optimize code.

We may note the above examples with `&&` and `||` being equivalent to `if` statements. That also means that these operators may boil down to branches during optimization, and branches hurt program performance. The less rules laid out about operator behavior, the easier it becomes to optimize away branches. Boolean logic tends to generate branches, whereas pure arithmetic might not.

(Picture source: original picture drawn just now by yours sincerely using Digikey Scheme-it)

Why does this post require moderator attention?

Short-circuit has a figurative meaning (3 comments)
Cannot be true or cannot be false (1 comment)
+2
−0

It means the program can give up early if checking the rest of a boolean expression is pointless.

For example, naively to evaluate `p and q` you must check the value of both `p` and `q`, and then do the `and` operation.

However, if you are a bit more clever, you'll see that when `p` is `False`, the result cannot be `True` no matter what `q` is. It's doomed already, so there's no point checking `q`. So we say `p` has short-circuited `q`.

A very common use is when people write things like `if foo() and bar():`. Both operands are executing some non-trivial code. If `bar()` happens to be a very computationally expensive function, it's useful to avoid running it when not necessary.

Besides performance, short circuits can reduce nesting. Another common idiom is: `if x is not Null and x.baz == "something":`. Without short circuit you would need two nested ifs, because the second expression would error out if `x` is indeed null. But with short circuits, if it is null, the program won't even attempt to check the second part so you can get away with this statement.

In electrical circuits, a short circuit is when electricity is provided a new (often unintended) path that it can use to bypass the real load (such as a lightbulb). Since it takes the path of least resistance, if you give it a shortcut, it will go through the shortcut without bothering to power your device. This is analogous to how the program skips the remainder of your expression when provided an easier way of completing evaluation.

Also, there are electronic versions of boolean expressions, such as AND gates. These use current yes/no as True/False. When building electronic circuits that evaluate booleans, you can have a literal short circuit mechanism.

Why does this post require moderator attention?