At Wed, 27 Nov 2024 22:52:59 -0000 (UTC), christos%astron.com@localhost (Christos Zoulas) wrote: Subject: Re: Style guide function variable initialization? > > No, it is correct. It means: > > int foo; > /* code not using foo*/ > /* code using foo */ > > sbould become: > > /* code not using foo*/ > int foo; > /* code using foo */ Just because something is possible according to the language standard doesn't mean it's good practice. Moving declarations away from the top of a block is bad practice and provably so from what I've read in software engineering studies. If I could find direct reference to the studies I'd share, but probably I'm thinking of work done by Derek M. Jones, perhaps even in his latest book: http://www.knosof.co.uk/ESEUR/ One thing Jones says in his "The New C Standard", that is arguably about this issue, is: "The concept of name space is not widely appreciated by C developers." Of course that's more about separate modules/libraries, but still... Probably nobody has studied software engineering practices related to C more widely and deeply than Jones, and his expertise goes much deeper in more general software engineering study. The book I reference _should_ be a MUST READ for anyone working with the details of C language standards conformance, even though it is not up-to-date beyond C90: http://www.knosof.co.uk/cbook/cbook.html See also: https://www.informit.com/articles/article.aspx?p=431105 I know from my own experience that such messy placement of declarations can more easily lead to "hidden" redefinitions and other related weirdness and confusion. It is far harder (for me at least, and arguably for many people) to create a good mental model of a piece of code if one can't find the declarations easily, i.e. at the top of the function, or top of an enclosing block at minimum. Personally if I go so far as to create an unnecessary block if I need to insert some code with minimal diffs which must introduce new variables, e.g.: /* fix foobar */ { int somevar; /* do something needing an extra "somevar" */ } Besides, it's more portable to keep to an older language standard. :-) Note I am slightly more on the fence about iterator declarations going right in the iterator statement (giving them block scope): for (int i = 0; i < somelim; i++) { blah[i] = i; } The same issue with "hidden" redefinitions can occur, but with good naming practices, and avoiding spaghetti code (e.g. nested loops common in too-long function bodies), it can be kept to a minimum. -- Greg A. Woods <gwoods%acm.org@localhost> Kelowna, BC +1 250 762-7675 RoboHack <woods%robohack.ca@localhost> Planix, Inc. <woods%planix.com@localhost> Avoncote Farms <woods%avoncote.ca@localhost>
Attachment:
pgpgRXScWnuoP.pgp
Description: OpenPGP Digital Signature