threads / patch / 13627

patchCodingGuidelines: Add a note to avoid assignments inside if()

Subject: [PATCH] CodingGuidelines: Add a note to avoid assignments inside if()

## tl;dr

2 messages between May 22, 2008 and May 25, 2008. Diffs are folded; open one to read it.

replies: 1people: 2as markdown or json

Miklos Vajna· May 22, 2008, 23:26 UTC · lore
Signed-off-by: Miklos Vajna <vmiklos@frugalware.org>
---

I just had to ask Dscho about this. Better if it's documented, I suppose.

 Documentation/CodingGuidelines |    2 ++
 1 files changed, 2 insertions(+), 0 deletions(-)
Show changes to Documentation/CodingGuidelines +2 −0
diff --git a/Documentation/CodingGuidelines b/Documentation/CodingGuidelines
index 994eb91..d2a0a76 100644
--- a/Documentation/CodingGuidelines
+++ b/Documentation/CodingGuidelines
@@ -89,6 +89,8 @@ For C programs:
    of "else if" statements, it can make sense to add braces to
    single line blocks.
 
+ - We try to avoid assignments inside if().
+
  - Try to make your code understandable.  You may put comments
    in, but comments invariably tend to stale out when the code
    they were describing changes.  Often splitting a function
-- 
1.5.5.1.357.g1af8b.dirty
Junio C Hamano· May 25, 2008, 05:17 UTC · re: Miklos Vajna · lore

Re: [PATCH] CodingGuidelines: Add a note to avoid assignments inside if()

Thanks.
FYI, recently in a nearby mailing list, we had this gem:
    From: Linus Torvalds <torvalds@linux-foundation.org>
    Subject: Re: [PATCH 3/5] isdn: fix integer as NULL pointer warning
    Date: Fri, 23 May 2008 08:08:57 -0700 (PDT)
    Message-ID: <alpine.LFD.1.10.0805230803290.3081@woody.linux-foundation.org>
    ...
    >  	len += sprintf(page+len, "%-16s %s\n", "type", s);
    > -	if ((s = cinfo->version[VER_DRIVER]) != 0)
    > +	if ((s = cinfo->version[VER_DRIVER]) != NULL)
    >  		len += sprintf(page+len, "%-16s %s\n", "ver_driver", s);
    For thigns like this (ie testing an assignment), I personally much prefer
            s = cinfo->version[VER_DRIVER];
            if (s)
                    len += sprintf(page+len, "%-16s %s\n", "ver_driver", s);
    over the uglier and unreadable version.
    IOW, testing assignments is good only when:
     - you have to do it because of syntax (ie notably in a "while()" loop)
     - there's some reason you want it to be a single statement (eg doing a 
       macro or other thing)
     - of the assignment is really simple, and the test is not against NULL or 
       zero.
    The reason for that "the test is not against NULL or zero" is that testing 
    for NULL and 0 is better done with just a "if (x)", and in an assignment 
    that just means either (a) a incomprehensible extra parenthesis just to 
    shut the compiler up or (b) changing the simple test into a stupid test 
    (ie doing "if (x != NULL)").
    (b) is much preferable to (a), but just doing it as two statements is 
    much preferable to either!

← back to recent threads