LLVM Coding Standards

Spacen Jasset spacenjasset at yahoo.co.uk
Mon Apr 11 15:31:47 PDT 2011


On 11/04/2011 20:58, spir wrote:
> [slightly OT]
>
> Hello,
>
> I'm reading (just for interest) the LLVM Coding Standards at
> http://llvm.org/docs/CodingStandards.html. Find them very interesting
> because their purposes are clearly explained. Below sample.
>
> Denis
>

That seem all fairly sensible. It also reminds me of open source 
projects written in C, where GOTO is used, like so:


HANDLE handle1 = open(...);

...
if (out_of_memory)
	goto cleanup;

if (invalid_format)
	goto cleanup;
...

cleanup:
    if (handle1)
       close(handle1);
    if (handle2)
     close(handle2);


This code uses the dreaded goto statement, but I belive you can see that 
the author is trying to make the code more readable, or at least get rid 
of the nested indents/multiple cleanup problem you inevitably come 
across at some points in C code. It does tend to be more readable than 
the alternative, too.

I think that people like to follow rules, that is as soon as they have 
internalised them and made them their own. What this means is that they 
often then follow them to a fault, and you get deeply nested, but 
"structured" code, where instead you would be better of with more 
logically linear code as in the case of the early exit. Coding standards 
should probably just say: try and write readable code. Everyone knows 
what readable code looks like. It just not always quick or easy to make 
it that way.


While I am on the subject, I've *always* thought major languages have 
poor loop constructs:


(A)

for (;;)
{
	std::getline(is, line);
	if (line.size() == 0)
		break;
	...some things...
}


You have to call getline always at least once, then you need to test if 
the line is empty to terminate the loop. So how do you do it another way?

(B)
std::getline(is, line);
while (line.size() != 0)
{
         ...some things...
	std::getline(is, line);
}

Isn't there something a bit wrong here? N.B. a do .. while doesn't help 
here either.



in (A) there is no duplication, in essence what I am saying, is that 
there should be a loop whereby you can put the exit condition where you 
need it, but *also* the compiler should check you have an exit condition 
to prevent mistakes. This whole WHILE vs DO vs FOR loops thing is 
strange to me.

Instead you could just have:

loop
{
  ...
  if (condition) exit;
  ...
}

instead of WHILE and DO. Whereby you *must* have an exit condition.


But I suppose you need a FOR loop because the following may be error prone.

int x=0;
loop
{
if x > 9 exit;
...
x++;
}


So you would then end up with a LOOP a FOREVER (perhaps which is for(;;) 
by convention anyway) and a FOR loop.

I'll put the coffee down now...







More information about the Digitalmars-d mailing list