Of the following, which is the preferred way of doing things, and why? Are there any specific situations in which it makes any difference, assuming that the function bar() does not take the value zero at any time?
Case 1: Test the truth value of both conditions
if ((foo = bar()) && foo < 0)
error();
Case 2: Test only the assigned variable
if ((foo = bar()) < 0)
error();
The preferred way is to separate them:
foo = bar();
if (foo < 0)
error();
Edit: This is better way for both readability and avoiding bugs, such as in your first case:
if (foo = bar() && foo < 0)
error();
That should probably be:
if ((foo = bar()) && foo < 0)
error();
The first one is plain wrong. Because of precedence rules, you get:
if (foo = (bar() && foo < 0))
error();
which is usually not what you expect.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With