Using &&
and ||
to control the evaluation is a very fundamental thing in
programming. As many already answered, they are using "Short Circuit Evaluation".
In some languages they are the same as and
and or
, but not in all. In e.g.
Ruby they do not mean exactly the same (as I know).
What would be a more straight forward way to write these?
You could say that using &&
and ||
instead of if ... else
is lazy
programming, but some people would say that using &&
and ||
structure is
the most straight forward.
If you will have an alternative (or a way of understand this better):
expr && echo "aa"
# is the same as
if expr; then
echo "aa"
fi
and
expr || echo "aa"
# is the same as
if ! expr; then
echo "aa"
fi
and
expr && echo "yes" || echo "no"
# is the same as
if expr; then
echo "yes"
else
echo "no"
fi
and of course a mix
if this && that; then
echo "yes"
else
echo "no"
fi
The "Short Circuit Evaluation" is a very important rule, and in some
situations the code is depending on this.
In this example (from VIM, but it's the same in many languages) there would be an exception if it doesn't work:
if exists("variable") && variable == 3 ...
If both sides was evaluated before deciding the result there would be an
exception if variable
isn't defined.
There have been some bad designed languages where both sides of e.g. &&
was
evaluated before the result was given, they were not so fun to use.
So:
if you like it; then
use it && be happy
else
use it || be happy
fi