"mdh" <md**@comcast.n etwrites:
Bart wrote:
You can't just use the 'if' as though it were an expression. You can
only use it in a complete statement as above.
Yes....I am beginning to see that!! :-)
What I had missed was that presumably when an expression does not
evaluate to '0', it could also be a negative value. (I had assumed it
would have to be '0'. This came up in a later exercise when using
recursion to express an integer as a string (exercise 4-12). It is
strange that in the process of learning, one thinks one understands a
concept until one gets to understand it better, invariably through
making a mistake.
That's correct. In an if statement "if (foo)", the expression "foo"
is evaluated and the condition is considered false if foo is equal to
zero (which can mean different things for different types), and true
if foo has any non-zero value.
But that's not the problem with the code you posted. You're using
something like "if (foo)" in a context that requires an expression.
"if (foo)" isn't an expression; it's a fragment of a statement. (An
expression, with a semicolon added, can be a statement, but a
statement cannot in general be used as an expression.)
"if (foo)" doesn't return or yield a value; it evaluates the condition
and then affects the program's control flow based on the result.
As jmcgill points out, the conditional operator, also known as the
ternary operator (because it happens to be the only operator that
takes three operands), can give you the effect of an if/else in an
expression context. Use it sparingly; it can easily be used to write
nearly illegible code. Something like
a = (b ? c : d);
is often clearer if it's written as
if (b) {
a = c;
}
else {
a = d;
}
--
Keith Thompson (The_Other_Keit h)
ks***@mib.org <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <* <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.