:: Re: [DNG] suggest parentheses aroun…
Página Inicial
Delete this message
Reply to this message
Autor: tilt!
Data:  
Para: dng
Tópicos Antigos: [DNG] (no subject)
Assunto: Re: [DNG] suggest parentheses around assignment used as truth value (Was: no subject)
Am 19.10.2015 um 10:03 schrieb Edward Bartolo:
> automated_scanner.c:521:2: warning:
> suggest parentheses around assignment used as truth value
> [-Wparentheses]
> if ( dir =opendir(IFACES_PATH) ) {


I recommend writing this instead at line 512 of automated_scanner.c:

    if (NULL != (dir = opendir(IFACES_PATH))) {


Reasoning:

    dir = opendir(...)


is an assignment that lets "dir" be "NULL" in case of error (it is
documented in the manpage of opendir(3) that it returns NULL in case of
error).

Furthermore, it is a behavior of the C assignment operator "=" that the
result of an assignment is the assigned value. This is why one can
write things like

    a = b = 1


Using an assignment as an if(...) condition this way is possible, but
there is a high risk of mistaking it with the check for equality
operator, "==":

    if(a = b)


is visually very close to

    if(a == b)


but they mean completely different things.

Also, using parentheses avoids confusion with operator precedence:

    a = b = 1


only works because "b = 1" is performed before "a = b"; for example,
while exposing the same behavior as the term above, it is visually
clearer to write

    a = (b = 1)


This is why the GNU C Compiler suggests performing the assignment in
parentheses if it is to be used as an "if(...)" condition.

The way I have written it, it is clearer that i first perform the
assignment "dir = opendir(...)" and afterwards explicity check that
"NULL" is not equal to the assigned value.

I generally would like to recommend writing statements as clearly as
possible whenever possible, but especially so in security relevant code
portions.

Kind regards,
T.