Tomás Ó hÉilidhe said:
Over on comp.lang.c++, we were dicussing the replacment of:
if (expr) Func();
with:
expr && Func();
My own initial reaction was that, if I saw the latter in code, I'd say
the programmer is playing games trying to impress with funky features. I
stated that "if" has this exact purpose in the language, and it should be
used for this.
But then one of the contributors replied saying that they use "if" for
the normal run of code, but then use && and || for error-checking code.
Sort of like:
FILE *pf;
if (input > 7)
{
pf = fopen("monkey","r");
pf || exit(EXIT_FAILURE);
}
To be honest, I quite like the idea. The error-checking code clearly
stands out from the "normal" code.
This is a terrible idea in C, for two reasons:
1) It's not common practise
2) It doesn't read logically.
In Perl (where this construct *is* common practise and idiomatic),
functions generally return a true value for success, so the line:
dosomething(...) or die "Couldn't open file";
uses the words "or die" in the same way that English uses them. In C,
functions generally return 0 for success, so the form in C would be:
dosomething(...) && myerrorfunc("Couldn't open file\n");
where the word "and" is used in precisely the opposite way from English.
fopen() returns a valid pointer for success and NULL for failure, so
this idiom happens to work for fopen(), but fclose() returns 0 (false)
for success and EOF (true) for failure, so this technique could never be
used consistently.