Coding standards

N

Natt Serrasalmus

After years of operating without any coding standards whatsoever, the
company that I recently started working for has decided that it might be a
good idea to have some. I'm involved in this initiative.

Typically I find that coding standards are written by some guy in the
company who has a way of coding that he likes and then tries to force
everybody else to write code the way he likes it, not for any rational
reason, but simply for the subjective way he likes it. I think this is
wrong.
This is particularly irksome when it comes to issues of code layout style
which has very little relevance to the execution of the code or the
readablility and maintenance of the code.

I also think it is wrong for coding standards to try to prevent idiots from
doing stupid things. No matter how stringent some standards are, somebody
stupid is going to find a way to do something stupid to the code. My point
is that instead of making the standard more restrictive on good coders, the
bad coders should be brought up to speed to be able to write good code, not
pandered to by the standard. For example there is the seemingly universal
attitude that fully bracketed
syntax is the way to go (this will stop the idiots). I strongly disagree.
There are many times that leaving out the braces where not necessary makes
for more readable code. It also reduces the maintenance of braces; the fewer
braces the easier it is to keep braces matched up. The problem is that I
think most coders are too lazy to be bothered to know exactly when they need
braces and when they don't. If you don't know, just stick them in everywhere
that it can't hurt. Lots and lots of braces means lots and lots of code to
maintain that doesn't need to be there.

I recently read a standard that prohibited use of the ternary (conditional
?) operator. I find that most C programmers just haven't bothered to learn
how to use it and don't want others to use it, because then they'll have to
figure it out. However I have also found that in most cases where it is
used, it can make the code much clearer even for those who are not
accustomed to its use.

a = (b == c) ? d : e;

Is just as understandable and more maintainable than

if (b==c) {
a = d;
}
else {
a = e;
}

In the first case it is obvious in one line that you are simply assigning a
value to a based on the condition. The use of the if statement makes for a
lot more code that is subject to error in maintenance.

Another issue that I have come across is the one way out of a function
issue. I contend that if there are conditions that warrant an earlier exit
from a function then the early exit should be taken. For eample:

int funct( int arg )
{

.....

if (condition) return ERROR;

....

return OK;

is much better than

int funct( int arg )
{
int retval = ERROR;
.....

if ( !condition) {
retval = OK;
(rest of function);
....
} /* end of if ( !condition) */

return retval;

In the first case you've been very clear as to what values are going to be
returned, you've reduced the number of braces involved and you've reduced
the indentation level of the major part of the function. The argument
against this is that there may be some clean up that needs to be done in a
function and this style may lead an idiot to exit the function with out
doing the clean up. My rebuttal is that number one, only a small minority of
functions have the requirement that the clean up be done before exiting the
function. Number two, the clean up should be a separate function anyway that
can be called from anywhere in the parent function and number three you just
can't count on the standard to protect the code from idiots anyway so why
pretend that it does?

A similar issue is this one:

if (condition) {
retval = func(arg );
}

If that condition has to be tested before each function then the condition
should be evaluated by the function instead:

retval = func( arg, condition);

....
int func( int arg, BOOLEAN condition)
{

if (!condition) return OK;

....
}


On the whole I consider less code to be more maintainable than lots of code.
Anywhere I can reduce the lines of code then that makes it easier to
maintain. For example:

if( condition)
{
retval = func( a, b);
}
else
{
retval = func( a, c);
}

if (retval != OK)
{
error_exit_func();
}

a much better way is

if ( !func(a, condition ? b : c ) error_exit_func();


Is there anybody out there who will agree with me on these issues or am I
the lone voice for this type of coding?
 
M

Michael Mair

Natt said:
After years of operating without any coding standards whatsoever, the
company that I recently started working for has decided that it might be a
good idea to have some. I'm involved in this initiative.

Typically I find that coding standards are written by some guy in the
company who has a way of coding that he likes and then tries to force
everybody else to write code the way he likes it, not for any rational
reason, but simply for the subjective way he likes it. I think this is
wrong.

Well, from the rest of your post one could get the impression
that you are just a more self-aware flavour of "this guy".
Your examples show preferences which may be more restrictive
for some programmers than other coding standards.

This is particularly irksome when it comes to issues of code layout style
which has very little relevance to the execution of the code or the
readablility and maintenance of the code.

This is correct. Sooner or later someone will become coding police
more interested in the right use of indentation, white-spaces,
comment styles and so on.
However, having had the dubious pleasure of coding in a group
where people did not care about the "details", I think that coding
rules which can be scribbled down on one piece of paper are the
best way to go. If you use cvs, even stuff like indentation can
be important enough to be put down on said sheet.

I also think it is wrong for coding standards to try to prevent idiots from
doing stupid things. No matter how stringent some standards are, somebody
stupid is going to find a way to do something stupid to the code. My point
is that instead of making the standard more restrictive on good coders, the
bad coders should be brought up to speed to be able to write good code, not
pandered to by the standard. For example there is the seemingly universal
attitude that fully bracketed
syntax is the way to go (this will stop the idiots). I strongly disagree.
There are many times that leaving out the braces where not necessary makes
for more readable code. It also reduces the maintenance of braces; the fewer
braces the easier it is to keep braces matched up. The problem is that I
think most coders are too lazy to be bothered to know exactly when they need
braces and when they don't. If you don't know, just stick them in everywhere
that it can't hurt. Lots and lots of braces means lots and lots of code to
maintain that doesn't need to be there.

If your company does not use editors which can keep up with braces,
then they may be in trouble...
Honestly, even though "full bracing" is unnecessary, this is one of
the rules which depend on the rest of your coding standard. If there
are no rules about indentation and brace placement or related issues,
the belt and braces (no pun intended) method may be safer.

I recently read a standard that prohibited use of the ternary (conditional
?) operator. I find that most C programmers just haven't bothered to learn
how to use it and don't want others to use it, because then they'll have to
figure it out. However I have also found that in most cases where it is
used, it can make the code much clearer even for those who are not
accustomed to its use.

a = (b == c) ? d : e;

Is just as understandable and more maintainable than

if (b==c) {
a = d;
}
else {
a = e;
}

In the first case it is obvious in one line that you are simply assigning a
value to a based on the condition. The use of the if statement makes for a
lot more code that is subject to error in maintenance.

Well, this depends. I would have placed the parentheses differently,
someone else might leave them out, a third might add all sorts of
parentheses.
However, banishing part of the language's operators or keywords is
only advisable in very special cases. I would be very wroth if
"for" and "do" were disallowed.

Another issue that I have come across is the one way out of a function
issue. I contend that if there are conditions that warrant an earlier exit
from a function then the early exit should be taken. For eample:

int funct( int arg )
{

....

if (condition) return ERROR;

...

return OK;

is much better than

int funct( int arg )
{
int retval = ERROR;
....

if ( !condition) {
retval = OK;
(rest of function);
...
} /* end of if ( !condition) */

return retval;

In the first case you've been very clear as to what values are going to be
returned, you've reduced the number of braces involved and you've reduced
the indentation level of the major part of the function. The argument
against this is that there may be some clean up that needs to be done in a
function and this style may lead an idiot to exit the function with out
doing the clean up. My rebuttal is that number one, only a small minority of
functions have the requirement that the clean up be done before exiting the
function. Number two, the clean up should be a separate function anyway that
can be called from anywhere in the parent function and number three you just
can't count on the standard to protect the code from idiots anyway so why
pretend that it does?

You are once more only advocating your own views.
Why not formulate a rule which allows only single exit points
for functions containing cleanup code. Whether this is reached
by state variables, goto or splitting the function into three parts
(initialization, work, cleanup) such that the rule only aims at
the actual cleanup routine, can be up to the programmers and
situation.

A similar issue is this one:

if (condition) {
retval = func(arg );
}

If that condition has to be tested before each function then the condition
should be evaluated by the function instead:

retval = func( arg, condition);

...
int func( int arg, BOOLEAN condition)
{

if (!condition) return OK;

...
}

Perfectly valid for this case. But if func already has seven
parameters, then you are probably doing yourself a disservice
by adding another one or two -- people will just get "blind"
with respect to the arguments.
Given your liking for short expressions you might just go for
condition && (retval = func(arg))

On the whole I consider less code to be more maintainable than lots of code.
Anywhere I can reduce the lines of code then that makes it easier to
maintain. For example:

if( condition)
{
retval = func( a, b);
}
else
{
retval = func( a, c);
}

if (retval != OK)
{
error_exit_func();
}

a much better way is

if ( !func(a, condition ? b : c ) error_exit_func();

Apart from the missing closing parenthesis, I think
that is too much. I would at least let the call to
error_exit_func() reside on a second line.

Is there anybody out there who will agree with me on these issues or am I
the lone voice for this type of coding?

Probably you will find some people who will agree with most
you said.

Without knowing the type and complexity of the code, one usually
can cobble together exactly what you proposed: A coding standard
fitted to the tastes of the creators.

I suggest you start from the purpose of the code and the needed
documentation level.
Then add rules like naming conventions for certain types of objects,
unified interfaces (source, destination, size or destination, source,
size or source, size, destination or ...)
If there is still some room on your sheet of paper, state rules
like "code such that it can be read like prose, avoiding inane
comments". Be specific about comment styles.
If there is still room for more rules, have a look at the bugs
which cost most time to find. Enforcing rules which reduce the
number of these bugs are a good idea. If this means that every
new module gets unit tests, so be it.
If there is still room for more rules, you cheated and went for
toilet paper...

Do not go for rules aiming at whatever makes you itch.
Go for the problems.
Reasons for the above order: If clear documentation is required,
bugs are found sooner, and people who invest enough thought
before coding automatically code in a less convoluted way.
Unified interfaces and naming rules save time.
Weeding out the "fit the quota" comments or other bad habits
by general rules is more effective than trying to cover all
positive good comment/bad comment situations.
If there is a pattern of how bugs get into the code breaking
it helps more than arguing about the intricacies of brace
placement. If you cannot find such rules, then you have found
the point in your software where redesign or alternative
solutions are needed...


HTH
Michael
 
B

Bart Goeman

Op Sun, 19 Dec 2004 18:05:06 -0500, schreef Natt Serrasalmus:
After years of operating without any coding standards whatsoever, the
company that I recently started working for has decided that it might be a
good idea to have some. I'm involved in this initiative.

Typically I find that coding standards are written by some guy in the
company who has a way of coding that he likes and then tries to force
everybody else to write code the way he likes it, not for any rational
reason, but simply for the subjective way he likes it. I think this is
wrong.

i think an arbitrary decision is (often) right.
that's what standards are all about, uniformity.
e.g. i would have liked that processor vendors had made a decision on
endianness, little or big, and everyone would conform to that standard.

maybe in some circumstances the other convention would be more usefull
(?), but the advantage of having one endianness would be _very_ big indeed!

i don't like these coding standard myself, everyone should code the way I
do :)
if ( !func(a, condition ? b : c ) error_exit_func();
IMHO this is too short. readability is very important. it should be
easy even for novice programmers.
but if novice programmers don't know ( ? : ) they should learn it instead
of prohibiting it in the coding standard
 
G

Gordon Burditt

After years of operating without any coding standards whatsoever, the
company that I recently started working for has decided that it might be a
good idea to have some. I'm involved in this initiative.

Most coding standards, if applied in the same way as an employee
dress code, would amount to something like "all employees shall
wear a size 6 red dress catalog # AC37626R from Macy's during working
hours" with no exceptions for the men or the pregnant.

Please consider that there are things that are not worth spending
a lot of time standardizing, such as the positioning of braces,
except to agree that outdenting is awful:

#include <stdio.h>
#include <stdlib.h>
int main(int argc, char **argv) {
if (argc < 2) {
printf("Usage: bulrfl filename\n");
}
exit(0);
}

Typically I find that coding standards are written by some guy in the
company who has a way of coding that he likes and then tries to force
everybody else to write code the way he likes it, not for any rational
reason, but simply for the subjective way he likes it. I think this is
wrong.

If you wish to standardize code layout, the best standard I can
think of is "All C code shall be run through GNU indent with the
following options before being checked into the source code control
system." (I really don't care what options you choose, as long as
outdenting is not selected, and I'm pretty sure it's not even
supported. If necessary, select which options are used by coin
flipping). Some source code control systems can even be made to
do this automatically.
This is particularly irksome when it comes to issues of code layout style
which has very little relevance to the execution of the code or the
readablility and maintenance of the code.

I also think it is wrong for coding standards to try to prevent idiots from
doing stupid things. No matter how stringent some standards are, somebody
stupid is going to find a way to do something stupid to the code. My point
is that instead of making the standard more restrictive on good coders, the
bad coders should be brought up to speed to be able to write good code, not
pandered to by the standard. For example there is the seemingly universal
attitude that fully bracketed
syntax is the way to go (this will stop the idiots).

I agree with braces being used even where optional (e.g. in an if) but
not for the reason "this will stop the idiots". I think it makes
it more readable.
I strongly disagree.
There are many times that leaving out the braces where not necessary makes
for more readable code. It also reduces the maintenance of braces; the fewer
braces the easier it is to keep braces matched up.

If by "matched up", you mean indented at the same level, let GNU
indent handle it. If you mean unbalanced, then leaving them out
is not going to help much, as you won't be any more consistent about
leaving both out as putting both in.
The problem is that I
think most coders are too lazy to be bothered to know exactly when they need
braces and when they don't. If you don't know, just stick them in everywhere
that it can't hurt. Lots and lots of braces means lots and lots of code to
maintain that doesn't need to be there.

If braces are "lots and lots of code", I think the code has a lot
more problems than braces.
I recently read a standard that prohibited use of the ternary (conditional
?) operator. I find that most C programmers just haven't bothered to learn
how to use it and don't want others to use it, because then they'll have to
figure it out. However I have also found that in most cases where it is
used, it can make the code much clearer even for those who are not
accustomed to its use.

a = (b == c) ? d : e;

Is just as understandable and more maintainable than

if (b==c) {
a = d;
}
else {
a = e;
}

I especially find it useful in certain debugging situations:

printf("Name: %s Address: %s\n",
(name == NULL) ? "(null)" : name,
(addr == NULL) ? "(null)" : addr );

where the introduction of temporary variables or replicating the
printf() is undesirable. It makes relating the %s and the argument
that's guaranteed not to be NULL easier.

When you've started nesting ?:, though, you've probably gone too far.
In the first case it is obvious in one line that you are simply assigning a
value to a based on the condition. The use of the if statement makes for a
lot more code that is subject to error in maintenance.
Another issue that I have come across is the one way out of a function
issue. I contend that if there are conditions that warrant an earlier exit
from a function then the early exit should be taken. For eample:

Generally, I agree here, because you end up with deeper-nested
conditionals, and near the end of the function, you have to look
carefully to see what error conditions you don't have to worry
about because you've already checked them.
int funct( int arg )
{

....

if (condition) return ERROR;

...

return OK;

is much better than

int funct( int arg )
{
int retval = ERROR;
....

if ( !condition) {
retval = OK;
(rest of function);
...
} /* end of if ( !condition) */

return retval;

In the first case you've been very clear as to what values are going to be
returned, you've reduced the number of braces involved and you've reduced
the indentation level of the major part of the function. The argument
against this is that there may be some clean up that needs to be done in a
function and this style may lead an idiot to exit the function with out
doing the clean up. My rebuttal is that number one, only a small minority of
functions have the requirement that the clean up be done before exiting the
function. Number two, the clean up should be a separate function anyway that

Cleanup can hardly ever be in a separate function because of all
the local variables involved. It really doesn't make much sense
to define a separate function with arguments of 7 pointers to free
if they were allocated and 2 open FILE *'s to close if they were
open. On the other hand, there is some use for closeifopen() defined
below if you are careful to initialize FILE *'s to NULL and set
them to NULL after closing a file. Now with memory allocation, you
don't need freeifallocated() since free() itself does the same thing.
can be called from anywhere in the parent function and number three you just
can't count on the standard to protect the code from idiots anyway so why
pretend that it does?

A similar issue is this one:

if (condition) {
retval = func(arg );
}

If that condition has to be tested before each function then the condition
should be evaluated by the function instead:

retval = func( arg, condition);

This depends on how the condition and the function are related.
If, for example, func is actually fopen(), and condition is whether
transaction logging is enabled, I can't see combining those into one
function. On the other hand, I can see defining

void closeifopen(FILE *arg)
{
if (arg != NULL)
{
fclose(arg);
}
return;
}

because the condition is related to whether you can successfully
execute the function at all, not some unrelated reason as to
why you might or might not want to execute it.
...
int func( int arg, BOOLEAN condition)
{

if (!condition) return OK;

...
}


On the whole I consider less code to be more maintainable than lots of code.
Anywhere I can reduce the lines of code then that makes it easier to
maintain.

Lines of code are a ridiculous metric, and you shouldn't use it.
A good coding standard will forbid counting lines of code for any
reason. Taking it to the extreme, all consecutive non-preprocessor
statements go on the same line until you hit line length limits.
For example:

if( condition)
{
retval = func( a, b);
}
else
{
retval = func( a, c);
}

if (retval != OK)
{
error_exit_func();
}

a much better way is

if ( !func(a, condition ? b : c ) error_exit_func();

No, I don't agree this is BETTER, and I think translating from the
first case to the second is a BUG. Who said OK is equal to zero?
Oh, yes, you're also missing a ).

But this really sucks:
if(condition){retval=func(a,b);}else{retval=func(a,c);}if(retval!=OK){error_exit_func();}
Is there anybody out there who will agree with me on these issues or am I
the lone voice for this type of coding?

I'll go along with you as far as translating the first part to
retval = func(a, condition ? b : c);

Gordon L. Burditt
 
C

Chris McDonald

After years of operating without any coding standards whatsoever, the

Pleasing to see a helpful and sensible discussion here without a flurry of
vitriolic comments claiming it to be off-topic (perhaps it's just a matter
of the weekend or timezones).
 
E

E. Robert Tisdale

Natt said:
After years of operating without any coding standards whatsoever,
the company that I recently started working for has decided that
it might be a good idea to have some. I'm involved in this initiative.

Typically, I find that coding standards are written
by some guy in the company who has a way of coding that he likes
and then tries to force everybody else to write code the way he likes it,
not for any rational reason, but simply for the subjective way he likes it.

Are you that guy?
I think this is wrong.

Yes, but are you that guy?
This is particularly irksome when it comes to issues of code layout style
which has very little relevance to the execution of the code or the
readablility and maintenance of the code.

You need to distinguish between *style* issues
and good programming practice.
I also think [that] it is wrong for coding standards
to try to prevent idiots from doing stupid things.

I don't think it's wrong.
I just don't think it works.
No matter how stringent some standards are,
somebody stupid is going to find a way to do something stupid to the code.
My point is that instead of making the standard more restrictive on good coders,
the bad coders should be brought up to speed to be able to write good code,
not pandered to by the standard.
For example, there is the seemingly universal attitude that fully bracketed
syntax is the way to go (this will stop the idiots). I strongly disagree.
There are many times that leaving out the braces where not necessary makes
for more readable code. It also reduces the maintenance of braces; the fewer
braces the easier it is to keep braces matched up. The problem is that I
think most coders are too lazy to be bothered to know exactly when they need
braces and when they don't. If you don't know, just stick them in everywhere
that it can't hurt. Lots and lots of braces means lots and lots of code to
maintain that doesn't need to be there.

I recently read a standard that prohibited use of the ternary
(conditional ?:) operator. I find that most C programmers
just haven't bothered to learn how to use it and don't want others to use it,
because then they'll have to figure it out. However, I have also found that
in most cases where it is used, it can make the code much clearer
even for those who are not accustomed to its use.

a = (b == c)? d: e;

Is just as understandable and more maintainable than

if (b == c) {
a = d;
}
else {
a = e;
}

It may be the only practical way to initialize a constant

const int a = (b == c)? d: e;
In the first case it is obvious in one line that
you are simply assigning a value to a based on the condition.
The use of the if statement makes for a lot more code
that is subject to error in maintenance.

Another issue that I have come across is the one way out of a function
issue. I contend that if there are conditions that warrant an earlier exit
from a function then the early exit should be taken. For eample:

int funct(int arg)
{

....

if (condition) return ERROR;

...

return OK;

is much better than

int funct(int arg)
{
int retval = ERROR;
....

if (!condition) {
retval = OK;
(rest of function);
...
} /* end of if ( !condition) */

return retval;

This is a bit of a "straw man" argument.
The problem is that functions which contain multiple exit points
are extremely difficult to read, understand an maintain.
Suppose, for example, that you need to modify the code
and malloc some temporary storage.
How do you ensure that that storage is free'd
before any of the multiple exits?

Maybe you can write more concise code
with one, two, three or mre return statements.
But where do you draw the line.
The line has been drawn, perhaps somewhat arbitrarily,
at a single point of return --
preferrably at the end of the function.
This simplifies cleanup, for example,
because the thread of execution is guaranteed
to run through any statements such as free
which are placed just before it.
In the first case you've been very clear as to what values are going to be
returned, you've reduced the number of braces involved and you've reduced
the indentation level of the major part of the function. The argument
against this is that there may be some clean up that needs to be done in a
function and this style may lead an idiot to exit the function with out
doing the clean up. My rebuttal is that number one, only a small minority of
functions have the requirement that the clean up be done before exiting the
function. Number two, the clean up should be a separate function anyway that
can be called from anywhere in the parent function
and number three you just can't count on the standard
to protect the code from idiots anyway so why pretend that it does?

A similar issue is this one:

if (condition) {
retval = func(arg);
}

If that condition has to be tested before each function,
then the condition should be evaluated by the function instead:

retval = func(arg, condition);

...
int func(int arg, BOOLEAN condition)
{

if (!condition) return OK;

...
}

On the whole I consider less code to be more maintainable than lots of code.
Anywhere I can reduce the lines of code
then that makes it easier to maintain. For example:

if(condition)
{
retval = func(a, b);
}
else
{
retval = func(a, c);
}

if (retval != OK)
{
error_exit_func();
}

a much better way is

if (!func(a, condition? b: c) error_exit_func();

Is there anybody out there who will agree with me on these issues
or am I the lone voice for this type of coding?

As far a coding style is concerned
that should be left up to each individual programmer.
Any rules regarding the style used for code repositories
can and should be resolved with a code reformatter such as indent

http://www.gnu.org/software/indent/indent.html

From: E. Robert Tisdale
Subject: Tisdale's C and C++ Style Guide
Newsgroups: comp.lang.c, comp.lang.c++
Date: 2003/01/13

Style is a very subjective and personal consideration.
C and C++ programmers develop or adopt a style
in order to make their code easier for themselves
and other programmers to read, understand and maintain.
If you are developing your own style, there are no rules
except that you should try to be consistent.
Otherwise, you should try to adopt a style
with which other C and C++ programmers are comfortable,
familiar or that they will at least recognize.
Personally, I try to use the same punctuation rules
that are used for ordinary (mathematical) typesetting.
Here are my recommendations:

Terminators always follow immediately after an expression

x@ for all @ in {?, :, ,, ;}

and are followed by at least one white space.
Write

x? y: z

instead of

x ? y : z

or

x?y:z

and write

void f(int, int, int); void g(double);

instead of

void f(int,int,int);void g(double);

for example.

There is no space
between some binary operators and their operands

x@y for all @ in {::, ., ->, .*, ->*, *, /, %, &, ^, |}

but there is always a space
between other binary operators and their operands

x @ y for all @ in {+, -, <<, >>;, <, <=, >, >=, ==, !=,
&&, ||, =, *=, /=, %=, +=, -=, <<=, >>=, &=, |=, ^=}

except when expressions appear as subscripts.
Write

x + y

instead of

x+y
and

x*y

instead of

x * y

for example.
But you may wish to write

A[i+1][j-1]

instead of

A[i + 1][j - 1]

for example to subscript array A.


Most unary prefix operators never have any whitespace
between themselves and their operands

@x for all @ in {::, ++, --, ~, !, -, +, &, *}

but others do

@ x for all @ in {sizeof, new, delete, delete [], throw}

No unary postfix operators

x@ for all @ in {[], (), ++, --}

ever have any whitespace between themselves and their operands.

Use the normal typesetting rules for parentheses (),
square brackets [], angle brackets <> and curly brackets {}.
No space after (, [, < or { and no space before ), ], > or }.
Write

(x)

instead of

( x )

or

(x )

or

( x)

and write

[x]

instead of

[ x ]

or

[x ]

or

[ x]

for example.
There are, of course, exceptions
where extra white space helps to make your code more readable:

double A[2][3] = {{ 1, -1, 0},
{-10, 11, -21}};


Don't give identifiers cryptic, mangled names.
Use ordinary, meaningful words, conventional symbols
or abbreviations with annotations.
Write

double distance, velocity, acceleration, mass, Force;

Force = mass*acceleration;

or

double x; // distance
double v; // velocity
double a; // acceleration
double m; // mass
double F; // force

F = m*a;

for example.

Don't rely on defaults. Make declarations explicit.
Write

int i = 1;

instead of

i = 1;

to declare and initialize integer i and write

class X {
private:
// Representation
int I;
public:
// Constructors
// ...
};

instead of

class X {
// Representation
int I;
public:
// Constructors
// ...
};

to define the private data members of class X for example.


Use indentation to emphasize scope.
Everybody is comfortable with standard indentation:

void f(void)
{
// indent
}

But I indent curly brackets to the scope of the function body:

void f(void)
{
// indent
}

And I include the open curly bracket with the function heading:

void f(void) {
// indent
}

to save a line of code.

I always indent just two spaces at a time and
I place just one statement on each line so that
there is usually room for a comment at the end of each line
beginning in column 33 or 41.

Write

if (condition) {
// statements
}

instead of

if(condition) {
// statements
}

and

while (condition) {
// statements
}

instead of

while(condition) {
// statements
}

to distinguish flow control structures from function calls.

I use

// comment

for comments in C++ and I reserve

/*
a = b;
// comment
b = c;
*/

to comment out code which may include comments.


If you find yourself in an environment
that requires you to conform to style rules with which you are not
comfortable,
consider investing a little time and effort in a program like astyle

Artistic Style
http://astyle.sourceforge.net/

which changes the appearance of C or C++ programs
by inserting or deleting whitespace.

Write

constant == variable

instead of

variable == constant

when comparing a variable to a constant for equality
so that if you write

constant = variable

by mistake, the compiler will detect the error.

I always write

x < y

or

x <= y

instead of

y > x

or

y >= x

when comparing two values so that the expression is true
when the left hand side is to the left of the right hand side
on the real number line.
 
L

Lawrence Kirby

On Sun, 19 Dec 2004 19:29:55 -0800, E. Robert Tisdale wrote:

....
This is a bit of a "straw man" argument.
The problem is that functions which contain multiple exit points
are extremely difficult to read, understand an maintain.

They can also be very easy to read and maintain. The error is in trying to
make this a style issue at all. Sometimes multiple returns are appropriate
sometimes they aren't.
Suppose, for example, that you need to modify the code
and malloc some temporary storage.
How do you ensure that that storage is free'd
before any of the multiple exits?

While this is a real issue there are many functions that are not affected
by it.

....
Write

constant == variable

instead of

variable == constant

I have to say this is a pet hate of mine. You are significantly
compromising the readability of the code for a limited case that many
compilers will warn about anyway if you ask them to. IMO it is far better
to write code that is more readable.
when comparing a variable to a constant for equality so that if you
write

constant = variable

by mistake, the compiler will detect the error.

I always write

x < y

or

x <= y

instead of

y > x

or

y >= x

when comparing two values so that the expression is true when the left
hand side is to the left of the right hand side on the real number line.

That doesn't always express the logic naturally, e.g.

for (x = max; min <= x; x--)

looks nasty to me. I'd have to flip the condition operation around in my
minf to feel comfortable with what it is doing. Writing x >= min here is
much more natural.

Lawrence
 
P

pete

Lawrence said:
I have to say this is a pet hate of mine. You are significantly
compromising the readability of the code for a limited case that many
compilers will warn about anyway if you ask them to. IMO it is far
better to write code that is more readable.

Is it really possible for someone who can understand
variable == constant
to get lost while trying to read
constant == variable
?
 
C

CBFalconer

Lawrence said:
.... snip ...

looks nasty to me. I'd have to flip the condition operation around
in my minf to feel comfortable with what it is doing. Writing
x >= min here is much more natural.

Do you realize you are arguing with Trollsdale?
 
T

Thomas Stegen

pete said:
Is it really possible for someone who can understand
variable == constant
to get lost while trying to read
constant == variable
?

No, but for me it break up the flow of reading. Not by much, but
breaking the flow for even less than a second is a problem and
increases the effort needed needlessly.

It does not need to be hard to read at all before it is to hard
to read. IOW, that something is only slightly harder to read is
a very strong argument against it.
 
C

Chris Croughton

Is it really possible for someone who can understand
variable == constant
to get lost while trying to read
constant == variable
?

Yes. Every time I see it (and I have cow orkers who do it a lot) I read
"1 == x" as "but 1 can never equal x, it's a constant". OK, it can be
understood eventually but it is non-obvious (in English I would never
say "if 10 is the number of cars", for instance) and delays finding
other errors. Since every compiler I have used in the last decade or so
will flag "if (x = 10)" as a potential error I find the "constant ==
variable" syntax unnecessarily confusing.

Chris C
 
D

dandelion

Thomas Stegen said:
No, but for me it break up the flow of reading.

Having made the same transition myself, I can attest it's a mere question of
getting used to it. The benefit of fishing out possibly unwanted assignments
outweighs the effort IMO.
It does not need to be hard to read at all before it is to hard
to read. IOW, that something is only slightly harder to read is
a very strong argument against it.

That's a good point, but can be solved with a little 'getting used to the
idea'.
However, I do not intend to embark on a private little style-war on this
subject.

"de gustibus non est disputandum" as the romans said.
 
C

Chris Croughton

You like those parentheses ?

My preference is to put the whole of the ternary expression within
parentheses, and additional parentheses for the condition only if it
ind/or the expressions are complex. So I'd write:

a = (b == c ? d : e);
a = ((b == c && d > e) ? (f + d*e) : (g + h*j));

I also put parentheses round expressions more complex than a simple
variable or constant (or sometime a simple function call) used in return
statements:

return 1;
return xyz;
return func(3);
return (a == b);
return (fred + bill*joe);

But that's my personal preferences, when working I conform to the local
style even when I dislike it...

Chris C
 
L

Lawrence Kirby

Do you realize you are arguing with Trollsdale?

I know who I was replying to, yes. I try to base my responses on the merit
of the article rather than opinion about who posted it. While style issues
are always subjective I don't see any reason to dismiss the post I replied
to as so unreasonable as to ignore it. And of course if something looks
reasonable but is wrong (not a comment on this case) then it should not be
left unchallenged in the newsgroup.

Lawrence
 
B

billh40

Chris said:
My preference is to put the whole of the ternary expression within
parentheses, and additional parentheses for the condition only if it
ind/or the expressions are complex. So I'd write:

a = (b == c ? d : e);
a = ((b == c && d > e) ? (f + d*e) : (g + h*j));

I also put parentheses round expressions more complex than a simple
variable or constant (or sometime a simple function call) used in return
statements:

return 1;
return xyz;
return func(3);
return (a == b);
return (fred + bill*joe);

But that's my personal preferences, when working I conform to the local
style even when I dislike it...

Chris C

Coding style standards are good for large teams. However, I try
to
make my code readable and with extensive comments so that I can know
what algorithms I had used when I review the code at a much later time
( 6 months or a year later). There are a number of papers recommending
coding styles. I try to abide by them whenever I can.

Bill Hanna
 
R

Richard Bos

pete said:
Is it really possible for someone who can understand
variable == constant
to get lost while trying to read
constant == variable

Why, yes. I expect to ask "Is the size of the block 4?", not "Is 4 the
size of the block?".

Richard
 
C

CBFalconer

Thomas said:
No, but for me it break up the flow of reading. Not by much, but
breaking the flow for even less than a second is a problem and
increases the effort needed needlessly.

It does not need to be hard to read at all before it is to hard
to read. IOW, that something is only slightly harder to read is
a very strong argument against it.

Please explain to me how:

thinga == thingb;

carries any different connotations than:

thingb == thinga;

although I will readily concede that, in C, replacement of '=='
with '=' will immediately attach special connotations.
 
L

Lawrence Kirby

Is it really possible for someone who can understand
variable == constant
to get lost while trying to read
constant == variable

Briefly, yes, because it isn't the natural idiom. The fact is that we read
left to right and even where an operation is commutative like this there
can be associations for what you expect on the left and on the right.
However it isn't as bad as when relational operators are used.

Lawrence
 
C

Chris Croughton

Please explain to me how:

thinga == thingb;

carries any different connotations than:

thingb == thinga;

The first one is more expected to change, in English. "Is the ship at
its destination?" makes a lot more sense than "Is the destination at the
ship?", although "Is ship 1 at ship 2?" (where both are variable) makes
sense.

I read C code in words, so I will mentally pronounce

if (var == 4)

as "if var is four", the alternative "if four is var" doesn't make much
sense.

Chris C
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Similar Threads


Members online

No members online now.

Forum statistics

Threads
473,766
Messages
2,569,569
Members
45,043
Latest member
CannalabsCBDReview

Latest Threads

Top