Path: csiph.com!eternal-september.org!feeder.eternal-september.org!reader01.eternal-september.org!.POSTED!not-for-mail From: Tim Rentsch Newsgroups: comp.lang.c Subject: Re: Coding style for small if statements Date: Sun, 16 Feb 2020 05:43:24 -0800 Organization: A noiseless patient Spider Lines: 52 Message-ID: <86o8tyfy0z.fsf@linuxsc.com> References: <20200131234613.59047e037939ceb549b8e6d6@gmail.com> <65de5d07-838a-4a5f-bd70-b8a263fc61d6@googlegroups.com> Mime-Version: 1.0 Content-Type: text/plain; charset=us-ascii Injection-Info: reader02.eternal-september.org; posting-host="5afe6ca82d77f883ab9def33834e0994"; logging-data="6778"; mail-complaints-to="abuse@eternal-september.org"; posting-account="U2FsdGVkX18uv/m/FSO9o0IOatoAX73n63I4jdInjQg=" User-Agent: Gnus/5.11 (Gnus v5.11) Emacs/22.4 (gnu/linux) Cancel-Lock: sha1:gJ4al1bqYgcmPkjKOc+nkJwxOCE= sha1:KnTPPeqQ+2+YsuF1zUPbDNGPDjc= Xref: csiph.com comp.lang.c:150047 John Bode writes: > On Friday, January 31, 2020 at 2:46:22 PM UTC-6, Anton Shepelev wrote: > >> Hello, all >> >> What do you think about the formatting and readability of >> the following code of mine from a display-setup function for >> the DOSBox emulator: >> >> if( dblh != dblw ) >> if( dblh ) gfx_flags |= GFX_DBL_H; else >> gfx_flags |= GFX_DBL_W; > > Gah. That merits a paddlin'. > > My personal rules: > > 1. Only omit braces for the innermost if (when applicable), > and only if it does not have an associated else; > 2. Braces and else go on their own lines; > 3. Braces line up with the if and else; > > To wit: > > if ( dblh != dblw ) > { > if ( dblh ) > { > gfx_flags |= GFX_DBL_H; > } > else > { > gfx_flags |= GFX_DBL_W; > } > } > > Unambiguous. It's clear which if the else belongs to, it's clear > which branch is taken based on the conditions, etc. You won't > introduce a bug if you decide to add a logging statement to either > branch. It sacrifices some vertical space (and a little visual > clutter), but nobody's going to come tracking you down later to > ask what the hell you meant. Remarkable. Advocating for a way of writing that uses eleven lines where a single line suffices. > Always write code assuming the person maintaining it is a violent > psychopath who knows where you live. If that were actually true you would already be dead, or at least maimed severely. :)