Subject: Re: Bluetooth protocol code
To: Ignatios Souvatzis <ignatios@cs.uni-bonn.de>
From: David Laight <david@l8s.co.uk>
List: tech-kern
Date: 12/13/2005 10:51:12
On Tue, Dec 13, 2005 at 10:18:09AM +0100, Ignatios Souvatzis wrote:
> What he said, and additional:
> 
> It encourages you to do all validity tests at the start of a function,
> and have the main piece of code at the first indentation level afterwards,
> instead of being deeply indented:
> 
> Other style:
> 
> sometype foo(parameters) {
> 	variable declarations;
> 	if (parameter1 is ok) {
> 		if (somevariable = allocationfunction(someparameter)) {
> 			if (somehandle = opennetworkconnection(somevariable) {
> 				dosomething(somevariable,somehandle,someotherparameter);
> 				return result;
> 			} else  {
> 				freeprocedure(somevariable);
> 				return some other error code;
> 			}
> 		} else {
> 			return error code;
> 		}
> 	} else {
> 		return error code
> 	}
> }

I've also seem people suggest the above layout because it means the
execution will follow through the common path without doing jumps.
However the compiler ended up generating a short conditional jump
around an unconditional long jump - so the jump was there anyway, and
the code was larger.

I certainly much prefer to see the error number by the test that
generates it, and 'returns' so I know there is nothing lurking at the
bottom of the function that gets executed in the error path.
(And never an 'else' after 'return' or 'break'.)

I'm also a strong believer in '} else {' having once been caught out
finding an 'else' on the next page [1] having already discarded all
memory of the corresponding 'if' and having to go back and re-parse
about 60 lines of code to see when the 'else' part got executed.

	David

[1] was a paper listing on fanfold paper, but still applies.

-- 
David Laight: david@l8s.co.uk