:: Re: [DNG] [OT] [Re: Studying C as t…
Top Page
Delete this message
Reply to this message
Author: Simon Hobson
Date:  
To: dng
Subject: Re: [DNG] [OT] [Re: Studying C as told. (For help)
KatolaZ <katolaz@???> wrote:

> Be careful, because conditional expressions in C are subject to
> "short-circuiting", meaning that only the minimum number of
> expressions sufficient to determine the value of a chain of && and ||
> will be evaluated. In particular, a chain of || expressions will be
> evaluated until there is one that evaluates to TRUE (!=0), while a
> chain of && is evaluated until there is one of them which evaluates to
> false (==0).


Indeed, and that is the whole point behind using them in this way. I use them a fair bit in shell programming :
eg
> [ <test expression> ] && something_to_do_if_test_matches


instead of
> if [ <test expression> ]
>   then
>     something_to_do_if_test_matches
> fi


or even on the command line as in :
> apt-get update && apt-get upgrade


There can be some situations that can trip you up, eg it might seem clever to do :
> some_command && another_command && echo "It worked !" || echo "Failed"



While a simple "echo" is unlikely to fail, if that step does fail (eg you are writing status to a file and there's a problem) then you could find both your 'success' and 'fail' commands being run.

Used intelligently the && and || operators can both aid readability and improve performance - but equally can be used to obfuscate (either deliberately or accidentally).