git/list[1] front-page[2] threads[3] people[4] search[5] about
 

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

From
Junio C Hamano <gitster@pobox.com>
Date
May 25, 2008, 05:17 UTC
Message-ID
<7vd4nbj72x.fsf@gitster.siamese.dyndns.org>
In-Reply-To
<1211498769-26871-1-git-send-email-vmiklos@frugalware.org>
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!
Previous: Miklos Vajna
Message 2 of 2 in “CodingGuidelines: Add a note to avoid assignments inside if()”
  1. CodingGuidelines: Add a note to avoid assignments inside if()Miklos Vajna, May 22, 2008
  2. Junio C HamanoMay 25, 2008

Read the whole thread, see it on lore, or plain text.

$ cat FOOTERMessages come from the public archive at lore.kernel.org/git, fetched every hour. The front page is chosen and written each morning by an AI editor and can be wrong; the threads themselves are the record. About and API. For agents: an MCP server at https://gitlist.dev/mcp, and any thread, story or person page as Markdown by adding .md to its URL (or sending Accept: text/markdown). Details in /llms.txt.