473,725 Members | 2,248 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Coding standards

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?


Nov 14 '05 #1
144 6900
Natt Serrasalmus wrote:
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
--
E-Mail: Mine is an /at/ gmx /dot/ de address.
Nov 14 '05 #2
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

Nov 14 '05 #3
>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(FIL E *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){r etval=func(a,b) ;}else{retval=f unc(a,c);}if(re tval!=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
Nov 14 '05 #4
>>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.

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).

--
Chris,
Nov 14 '05 #5
Natt Serrasalmus wrote:
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*accelerati on;

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.
Nov 14 '05 #6
On Sun, 19 Dec 2004 19:29:55 -0800, E. Robert Tisdale wrote:

....
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.


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
Nov 14 '05 #7
Lawrence Kirby wrote:

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

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.


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

--
pete
Nov 14 '05 #8
Natt Serrasalmus wrote:
a = (b == c) ? d : e;


You like those parentheses ?

--
pete
Nov 14 '05 #9
Lawrence Kirby wrote:
.... 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?

--
Chuck F (cb********@yah oo.com) (cb********@wor ldnet.att.net)
Available for consulting/temporary embedded and systems.
<http://cbfalconer.home .att.net> USE worldnet address!

Nov 14 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

5
3616
by: David Inada | last post by:
Looking for any info on coding standards for ASP? Any tools that help with the review/formatting of code? Is it done mainly for the jscript/vbscript components? David
3
2058
by: ganesan | last post by:
Hi Guys, Could any one knows the best coding standards styles(with variable declarations for c#) . and if any links or site with the best coding standards for .NET send me those links regards Ganesan
4
2295
by: dotNetDave | last post by:
About three weeks ago I released the first .NET coding standards book titled "VSDN Tips & Tricks .NET Coding Standards". Here is what the famous author/ speaker Deborah Kurata says about it: "David McCarter once again demonstrates his knack for pulling best practices into one cohesive unit with his new book "VSDN Tips and Tricks: .NET Coding Standards". This book includes everything from how to set up your project to how to declare...
5
5406
by: db2sysc | last post by:
ALl. Is it possible to get MS ACCESS CODING STANDARDS? TIA
7
2566
by: Ralph Lund | last post by:
Hi. I am starting a new project with C#. I am searching for "good" coding conventions. I know that there are some coding conventions from microsoft, (but they are very extensive and not clear). In the example programs of Microsoft they use different coding conventions: private members sometimes with underscore, sometimes without; when calling a method sometimes: method(param1, param2) or method ( param1, param2) (with or without...
7
4959
by: Robert Seacord | last post by:
The CERT/CC has just deployed a new web site dedicated to developing secure coding standards for the C programming language, C++, and eventually other programming language. We have already developed significant content for the C programming language that is available at: https://www.securecoding.cert.org/ by clicking on the "CERT C Programming Language Secure Coding Standard"
3
1778
by: editormt | last post by:
A recent poll asked if programming standards are used by development organisations... and if they are controlled. None: 20% Yes, but without control: 49% Yes, with control: 31% Participants: 369 Source: Methods & Tools (http://www.methodsandtools.com)
0
1675
by: pat | last post by:
CodeCheck Coding Standard's Support As a free service to our customers we offer support in developing "rule-files" for automating corporate coding standards. If you have a coding standard that you wish to automate please send the standard to us in PDF format so we can assist in developing the automation with codecheck. If you are developing codecheck rule-files and have a particular
9
2099
by: dom.k.black | last post by:
Can anyone recommend a good existing C++ coding standard - parctical, pragmatic and sensible? A company I joined recently are moving from C to C++, they are very much into coding standards. But I have a horibble feeling they might get a C programmer to write the C++ standard. Would be nice to be able to suggest an existing standard.
0
8889
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8752
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
9401
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
0
9257
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
9179
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
6011
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
0
4784
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
2
2637
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
3
2157
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.