Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the most appropriate way to assign and test a variable in an if statement?

Tags:

c

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();
like image 910
heuristicus Avatar asked Nov 01 '12 11:11

heuristicus


2 Answers

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();
like image 113
MByD Avatar answered Oct 14 '22 11:10

MByD


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.

like image 44
Olaf Dietsche Avatar answered Oct 14 '22 12:10

Olaf Dietsche