Stylistic questions on UNIX C coding.

P

Poster Matt

Hi,

I've a few questions concerning style when programming C on UNIX systems. I
don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15 years, I'm
finding it hard to get used to DEFINES in all capitals. Is it really frowned on
not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.


2. My personal variable and function naming style is camel case, with variable
names beginning with a lower case char and function names not. Is that
acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);


3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
120 chars I start thinking this might not look great in someone else's editor.


4. Does anyone care where the pointer * is? I prefer keeping to next to the
type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;


5. On a slightly different note, I've been handling my error messages by using
#define string constants in a header file. I saw some code which did this and it
looked good to me. Is that standard practise, if not what is?

EG. #define ErrorDirNotFound "The directory was not found."


There are so many style guides out there, most of them say contradictory things
at one point or another. What do the pros do?

Finally, before someone points this out... I know if I'm coding for myself, and
not following somebody else's stylistic requirements, I can do whatever I want.
However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

Thanks and regards, etc.
 
J

Julienne Walker

Hi,

I've a few questions concerning style when programming C on UNIX systems. I
don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15 years, I'm
finding it hard to get used to DEFINES in all capitals. Is it really frowned on
not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

All caps is merely a convention so that macros are easier to see. If
you don't want to follow that convention, feel free. Though keep in
mind that conventions are there for a reason. The preprocessor has
proven troublesome enough over the years to warrant having macros
stand out a bit. ;-)
2. My personal variable and function naming style is camel case, with variable
names beginning with a lower case char and function names not. Is that
acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

That's fine. I see that style often.
3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
120 chars I start thinking this might not look great in someone else's editor.

I try to keep each line under 100 characters (80 if possible). It's
less about monitor size than it is about easily reading my code at a
glance.
4. Does anyone care where the pointer * is? I prefer keeping to next to the
type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

Just make sure you're consistent and nobody will care. :)
5. On a slightly different note, I've been handling my error messages by using
#define string constants in a header file. I saw some code which did this and it
looked good to me. Is that standard practise, if not what is?

EG. #define ErrorDirNotFound "The directory was not found."

That's acceptable. Though keep in mind that in the age of
internationalization and localization, hard coding string literals
makes your code harder to port to other spoken languages.
There are so many style guides out there, most of them say contradictory things
at one point or another. What do the pros do?

The pros are just as contradictory as the style guides. Pick a style
you like and run with it, with the caveat that over time your tastes
(and as a result, your style) will evolve.
Finally, before someone points this out... I know if I'm coding for myself, and
not following somebody else's stylistic requirements, I can do whatever I want.
However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

You can make bad code look pretty and it's still bad code. But in my
experience, good code has never looked ugly. Good aesthetics seems to
come naturally if you focus on writing the best code possible.
 
F

Fred

All caps is merely a convention so that macros are easier to see. If
you don't want to follow that convention, feel free. Though keep in
mind that conventions are there for a reason. The preprocessor has
proven troublesome enough over the years to warrant having macros
stand out a bit. ;-)



That's fine. I see that style often.


I try to keep each line under 100 characters (80 if possible). It's
less about monitor size than it is about easily reading my code at a
glance.



Just make sure you're consistent and nobody will care. :)

Except that it is very error-prone to do so.

In C, the asterisk is associated with the variable name, not the type
specifier.
I've seen this so many times:

char* x, y;

Here, x a pointer to char, but y is a char.

Much clearer to show what you really intended:

char *x, *y; /* Both pointers */
or
char *x, y; /* One a pointer, one not */
 
J

James Harris

Hi,

I've a few questions concerning style when programming C on UNIX systems. I
don't want to look like an amateur. :)

As a fellow amateur in C....
1. Having been programming in higher level languages for the last 15 years, I'm
finding it hard to get used to DEFINES in all capitals. Is it really frowned on
not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

While I use them I don't like all caps for #defined values for two
reasons

1) #defined values don't seem to me too far removed from global
parameters. Indeed if we change them to parameters in a function call
they lose upper case status. The two uses are similar. To my mind the
format of the names should also be similar.

2) I'd prefer to reserve all caps for macros. Then they serve as a
warning that parameters are not guaranteed to be evaluated exactly
once.

Many libraries use all caps for their constants.

You could also define constants in enums rather than in #defines.
2. My personal variable and function naming style is camel case, with variable
names beginning with a lower case char and function names not. Is that
acceptable, if not what is?

You'll probably get advised to stick to whatever coding standards your
project team members use. Also, when changing someone else's code,
stick to the standards used therein. For your own projects you could
use

first_name
firstname
FirstName
firstName
3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
120 chars I start thinking this might not look great in someone else's editor.

Again, use existing coding standards if there are any. My monitor is
also wide but I prefer to keep to 80-columns because you never know
what size monitor the code will subsequently be edited on.
4. Does anyone care where the pointer * is? I prefer keeping to next to the
type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

It's normally as the latter due to

char* FirstName, ch, *p;
char *FirstName, ch, *p;

Regardless of which form is used I think only ch will be a char
variable - i.e. "char*" can be misleading. The other variables will be
pointers. Someone will correct me if I'm wrong. Though you are right
in principle, C does not cleanly segregate type and name. For example

int func(int);

This declares the name func but the type information is scattered all
over such declarations.
5. On a slightly different note, I've been handling my error messages by using
#define string constants in a header file. I saw some code which did this and it
looked good to me. Is that standard practise, if not what is?

EG. #define ErrorDirNotFound "The directory was not found."

That's much better than sprinkling messages throughout the code. If
followed consistently it makes clear what messages the code can issue.
Apart from clarity that would help if you ever want to release your
code in another human language. There are better ways with more
mechanism.

You may need a way to include variable values in your messages.
There are so many style guides out there, most of them say contradictory things
at one point or another. What do the pros do?

Finally, before someone points this out... I know if I'm coding for myself, and
not following somebody else's stylistic requirements, I can do whatever I want.
However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

Check some examples: K&R2, C Unleashed, books by Douglas Comer, the
Linux source etc. Also there is a FAQ entry for style issues:

http://c-faq.com/style/index.html

James
 
L

Lew Pitcher

Hi,

I've a few questions concerning style when programming C on UNIX systems.
I don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15
years, I'm finding it hard to get used to DEFINES in all capitals. Is it
really frowned on not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

CamelCase is acceptable, with the caveat that the programmer (you, or
whomever reads your code) should be able to distinguish the difference
between a macro and a variable.
2. My personal variable and function naming style is camel case, with
variable names beginning with a lower case char and function names not. Is
that acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

Again, CamelCase is acceptable.
3. Is there an accepted maximum line length? I've got a 24" monitor, if I
reach 120 chars I start thinking this might not look great in someone
else's editor.

Somewhere around 80 characters per line is the norm. That facilitates both
on-screen review and editing as well as printing and emailing of code.

4. Does anyone care where the pointer * is? I prefer keeping to next to
the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

That's acceptable, but prone to error.
Given
char* firstName lastName;
what is the type of <lastName>?

If you read the declaration and answered that <lastName> is of char* type,
then you would be wrong. The language groups type modifiers to the defined
object, and not to the base type. Visually grouping the modifiers contrary
to how the language groups them can lead to programmer mis-interpretation
and error.
5. On a slightly different note, I've been handling my error messages by
using
#define string constants in a header file. I saw some code which did this
#and it
looked good to me. Is that standard practise, if not what is?

EG. #define ErrorDirNotFound "The directory was not found."

Most development groups I've worked with would find that practice
acceptable.
There are so many style guides out there, most of them say contradictory
things at one point or another. What do the pros do?

Usually, the pros do what the other pros that they are working with do.
Computer languages are a convenience to the /programmer/, not to the
computer. The rules (both at a language level, and at a developer level)
are set to make it easy for a programmer to write code, and for other
programmers to read (and often rewrite) it. So long as you apply your style
rules consistently (so that there are no unexpected deviations), things
should work out.
Finally, before someone points this out... I know if I'm coding for
myself, and not following somebody else's stylistic requirements, I can do
whatever I want. However I'd like my code to be 'acceptable looking' to
the wider UNIX C community.

/Which/ "UNIX C community"? Some communities have their own coding styles
("the one true style", or the K&R style, or the "Linux Kernel stye", for
instance), and no one set of rules will make your code acceptable to all of
the communities out there.

The best I can give you is to
a) be consistant, and
b) be simple
in your coding. Don't do the unexpected; once you've established a pattern,
stick with it until there is good reason to change. Document the change
ahead of time. Don't over-complicate things. The point is to make your code
easy to read and understand at the /human/ level.
 
S

Seebs

1. Having been programming in higher level languages for the last 15 years, I'm
finding it hard to get used to DEFINES in all capitals. Is it really frowned on
not to do so? Is CamelCase acceptable?

It'll work, but people will find it surprising. All-caps as a warning that
something is a macro or other manifest constant is pretty canonical.

But you'd normally spell that one "MAX_FILES".
2. My personal variable and function naming style is camel case, with variable
names beginning with a lower case char and function names not. Is that
acceptable, if not what is?

I dislike it, anyway. Convention is words_with_underscores().
EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

Also, "Num" doesn't need to be there.
3. Is there an accepted maximum line length? I've got a 24" monitor, if I reach
120 chars I start thinking this might not look great in someone else's editor.

80ish is preferred. Lines exceeding 80 will generally not be accepted by a
lot of projects unless there's a VERY good reason.
4. Does anyone care where the pointer * is? I prefer keeping to next to the
type, rather than next to the variable name.
EG. I like: char* firstName; and not so much: char *firstName;

You are wrong.

I mean, sure, it compiles, but consider:

char* x, y;

By contrast:
char *x, y;
makes it clear that you are aware that the * modifies the variable, not the
type.
5. On a slightly different note, I've been handling my error messages by using
#define string constants in a header file. I saw some code which did this and it
looked good to me. Is that standard practise, if not what is?
EG. #define ErrorDirNotFound "The directory was not found."

No. Look into gettext() if you need to do this, or just put them in
literally.
There are so many style guides out there, most of them say contradictory things
at one point or another. What do the pros do?

I use the Linux kernel style guide and/or the BSD style guide, which are
basically compatible. Ignore the GNU coding standards, they're awful.
Finally, before someone points this out... I know if I'm coding for myself, and
not following somebody else's stylistic requirements, I can do whatever I want.
However I'd like my code to be 'acceptable looking' to the wider UNIX C community.

It's a good effort. I do have to say, though... It's odd that you've managed
a complete sweep of, for every stylistic decision described above, picking
the opposite of the general convention in the UNIX world. Where did you pick
up these preferences?

-s
 
R

Rich Webb

I try to keep each line under 100 characters (80 if possible). It's
less about monitor size than it is about easily reading my code at a
glance.

Typographers, who study this thing with the fervor that programmers
bring to brace styles, would tend to agree. There are always reasonable
exceptions but a line length that's 70-80 characters (monospaced) seems
to be a sweet spot for comprehension.
Just make sure you're consistent and nobody will care. :)

Except there's the danger in having one's thoughts focused elsewhere
when adding the next piece, and getting

char* firstName, lastName;
 
J

Julienne Walker

Except that it is very error-prone to do so.

It's only error prone if you have multiple variables in a declaration
statement (which the OP's example did not). That itself is often
viewed as an unsafe practice.
 
E

Eric Sosman

Hi,

I've a few questions concerning style when programming C on UNIX
systems. I don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15
years, I'm finding it hard to get used to DEFINES in all capitals. Is it
really frowned on not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

All-caps is one of those conventions that's widely adopted,
although there's no inherent linguisic necessity for it (indeed,
some macros required by the C Standard itself are lower-case).
People are accustomed to seeing macro names in upper-case only,
and since macros can look like functions but behave differently
(consider `x = MIN(y,z)' vs `x = MIN(y, f_with_side_effects())'),
the coder must sometimes know which is being used. Recommendation:
Stick with upper-case macro names to forestall confusion.
2. My personal variable and function naming style is camel case, with
variable names beginning with a lower case char and function names not.
Is that acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

Use whatever works for you, and for the others who read the
same body of code. If you're working on existing code, stay with
whatever conventions it already uses. If you're writing new code
(that's not in association with existing code), use what you like.
3. Is there an accepted maximum line length? I've got a 24" monitor, if
I reach 120 chars I start thinking this might not look great in someone
else's editor.

Really long lines -- especially in blocks that cover several
consecutive lines -- can be hard to read because the eye may have
trouble maintaining vertical "registration" while flipping back
and forth between the end of one line and the start of the next --
oh, damn, I skipped down two again! Usual practice is to use
narrower lines than yours, allowing the line to be seen as a whole
rather than traced out in multiple horizontal jumps. Seventy to
eighty characters are a typical length (although that range is in
part due to hysterical raisins).
4. Does anyone care where the pointer * is? I prefer keeping to next to
the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

If you're firm about declaring only one identifier per line,
this is fine. But the minute you write

char* firstPtr, finalPtr;

.... you're going to be unpleasantly surprised.
5. On a slightly different note, I've been handling my error messages by
using #define string constants in a header file. I saw some code which
did this and it looked good to me. Is that standard practise, if not
what is?

EG. #define ErrorDirNotFound "The directory was not found."

This could turn out to be helpful in translating the messages
someday: "Das Verzeichnis wurde nicht gefunden." On the other hand,
there are more flexible ways to deal with this than to compile
separate versions for German, French, Klingon, ...
There are so many style guides out there, most of them say contradictory
things at one point or another. What do the pros do?

Contradict each other, of course! Why did you ask?
Finally, before someone points this out... I know if I'm coding for
myself, and not following somebody else's stylistic requirements, I can
do whatever I want. However I'd like my code to be 'acceptable looking'
to the wider UNIX C community.

From the Eighth Commandment: "... thy creativity is better
used in solving problems than in creating beautiful new impediments
to understanding." The Commandment speaks of brace styles, but
the point applies with equal force to other stylistic choices.
 
R

Rainer Weikusat

Poster Matt said:
1. Having been programming in higher level languages for the last 15
years, I'm finding it hard to get used to DEFINES in all capitals. Is
it really frowned on not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

The problem with the preprocessor is that it work at the level of
preprocessing tokens and this means that, if preprocessor macros don't
live in a unique namespace, unintended substitutions can happen
easily, for instance, of subroutine names, and errors caused by this
are difficult to track down.

[...]
2. My personal variable and function naming style is camel case, with
variable names beginning with a lower case char and function names
not. Is that acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

CamelCase was invented for the Xerox Alto whose keyboard didn't have
an underscore character. Since 'object oriented programming' was also
(mostly) invented in the same context, 'OO-programmers' of today still
work around this hardware deficiency of the 1970s.
TheReasonThatTextsAreNotWrittenLikeThisIsBecauseReadibiltyIsCrappyThen.
So_use_a_visually_distinct_separator_character. People using scripts
based on the Roman alphabet have abandoned the Roman writing
convention to not use separators more than thousand years ago. Don't
reinvent it.

[...]
4. Does anyone care where the pointer * is? I prefer keeping to next
to the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

C knows about three kinds of derived types, arrays

char a[];

Pointers to functions

char (*a)();

and pointers

char *a;

Don't special-case on of these three cases because of a lack of
understanding of the C type system.

Lastly, please don't ask questions like this in public.
 
K

Keith Thompson

Poster Matt said:
I've a few questions concerning style when programming C on UNIX
systems. I don't want to look like an amateur. :)

1. Having been programming in higher level languages for the last 15
years, I'm finding it hard to get used to DEFINES in all capitals. Is
it really frowned on not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

The convention is to use all-caps for macro names, unless you're
deliberately hiding the fact that something is a macro.
2. My personal variable and function naming style is camel case, with
variable names beginning with a lower case char and function names
not. Is that acceptable, if not what is?

EG:
Variables: int numFiles = 0;
Functions: int CountNumFilesInDir(char* path);

A lot of people dislike camel case (my own preference is lower case
with underscores for most things), but it's a common and widely
accepted style. If you're working on an existing project, you should
follow the existing style (this applies to all these rules).
3. Is there an accepted maximum line length? I've got a 24" monitor,
if I reach 120 chars I start thinking this might not look great in
someone else's editor.

80 columns.
4. Does anyone care where the pointer * is? I prefer keeping to next
to the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

The usual C style is
char *firstName;
The usual C++ style is
char* firstName;
There's no language-level reason for the difference; C and C++ syntax
are the same at this level. I think it's just that Kernighan and
Ritchie preferred the first form, and Stroustrup preferred the second.

If you're going to be programming in C, I recommend the first form,
both because it's the usual convention and because it follows the
syntax of the langauge. When the compiler parses:

char * firstName ;

"*" and "firstName" are grouped together. What the declaration really
means is that the expression "*firstName" is of type char; it follows
from this that firstName is of type char*. C declarations usually
follow a "declaration follows use" format (though not 100%
consistently).

If you choose to use the second style, you should avoid declaring
multiple objects in a single declaration. Others have pointed out
that this:
char* foo, bar;
is either misleading or wrong. The solution, whichever style you
use, is to declare foo and bar separately:

char *foo; /* or char* foo; if you insist */
char bar;

[...]
 
B

BruceS

On 2010-02-24, Poster Matt <postermatt@no_spam_for_me.org> wrote:

I dislike it, anyway.  Convention is words_with_underscores().

FWIW, I prefer the camel case style, though I don't capitalize
function names. If I'm maintaining someone else's code (and don't
expect to take it over), I follow their style. If I'm working with a
team, the team usually agrees on a style.
You are wrong.

I mean, sure, it compiles, but consider:

        char* x, y;

By contrast:
        char *x, y;
makes it clear that you are aware that the * modifies the variable, not the
type.

Absolutely with Seebs on this. The first style clearly implies that x
and y are both pointers to characters.

<snip>

I would like to add that, as long as you're trying to use good style,
for God's sake don't use the wrong indentation style. If you put your
opening braces on the same line as your conditional, you'll just look
like a fool in front of your friends and colleagues.
 
K

Keith Thompson

Rainer Weikusat said:
4. Does anyone care where the pointer * is? I prefer keeping to next
to the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

C knows about three kinds of derived types, arrays

char a[];

Pointers to functions

char (*a)();

and pointers

char *a;

Array types, structure types, union types, function types, and pointer
types are all derived types (C99 6.2.5).
Don't special-case on of these three cases because of a lack of
understanding of the C type system.

But it might be acceptable to special-case on some cases *with*
an understanding of the C type system. I prefer "char *a;" myself,
but there's a valid argument that "char* a;" makes it more obvious
that's meant (that a is of type char*). As long as you also avoid
declaring multiple objects in a single declaration, it doesn't
necessarily cause any problems.
Lastly, please don't ask questions like this in public.

Why not? Or are you just being rude?
 
J

James Harris

....
I would like to add that, as long as you're trying to use good style,
for God's sake don't use the wrong indentation style.  If you put your
opening braces on the same line as your conditional, you'll just look
like a fool in front of your friends and colleagues.

Snobbish nonsense!
 
W

William Hughes

There are so many style guides out there, most of them say contradictory things
at one point or another. What do the pros do?


Among other things write style guides.
(i.e. what makes you think the pros are
not contradictory)

The only near universal conventions that I can
identify are

- macros should be upper case
- lines should not exceed 80 characters

For the rest, choose what you are most comfortable
with, always remembering that good code comes first.

(There have been lots of pros and cons pointed
out for your chosen style. I have little to add;
putting all error strings in one place seems
like a good idea, but something a little more flexible
than simple macros would seem in order.)

- William Hughes
 
E

Ersek, Laszlo

It'll work, but people will find it surprising. All-caps as a warning that
something is a macro or other manifest constant is pretty canonical.

But you'd normally spell that one "MAX_FILES".

(
And not FILES_MAX, as _MAX is a reserved suffix (in the X/Open (or
POSIX) Name Space).

http://www.opengroup.org/onlinepubs/007908775/xsh/compilation.html#tag_000_002_001
http://www.opengroup.org/onlinepubs/9699919799/functions/V2_chap02.html#tag_15_02_02
)

I dislike it, anyway. Convention is words_with_underscores().

I agree. However, I'd like to mention, as a counter-example, some C
language X client libs using CamelCase.

http://en.wikipedia.org/wiki/Xlib
http://en.wikipedia.org/wiki/Intrinsics
http://en.wikipedia.org/wiki/Motif_(widget_toolkit)

80ish is preferred. Lines exceeding 80 will generally not be accepted by a
lot of projects unless there's a VERY good reason.

Yes, a source formatted 80 columns wide works nicely on a character
console. And on a 24" TFT in 1920x1200, you can put two such windows
side by side, or have a web browser or a PDF viewer open beside the
source window, or diff two versions side by side without having to
scroll horizontally.

No. Look into gettext() if you need to do this, or just put them in
literally.

Or, for a bit more portable (and harder to use) approach:

http://www.opengroup.org/onlinepubs/007908775/xsh/catopen.html
http://www.opengroup.org/onlinepubs/007908775/xcu/gencat.html

The idea is that you translate printf() style format strings into
different natural languages, making heavy use of %n$ "position
specifiers", so that you can change the order the arguments are printed
in, without changing the order they are passed to *printf() (ie. without
changing the code).

http://www.opengroup.org/onlinepubs/007908775/xsh/fprintf.html#tag_000_008_809

catgets() allows/forces the programmer to supply a default string, which
is very useful.

(Not that I'd believe in software internationalization at all, having
seen *no* software correctly *and* understandably translated from
English to Hungarian, for example.)

It's odd that you've managed
a complete sweep of, for every stylistic decision described above, picking
the opposite of the general convention in the UNIX world. Where did you pick
up these preferences?

I'd have guessed Java, but as Rainer Weikusat points out in
<[email protected]>, CamelCase and co. originate from
much earlier. (Thanks for the interesting historical tidbit, Rainer!)

Cheers,
lacos
 
E

Ersek, Laszlo

...


Snobbish nonsense!

I've actually laughed out loud when I've read Bruce's part above; it's
so blatant that I'm almost completely sure it was meant as irony.
(Perhaps so is your response, too.)

Cheers,
lacos
 
S

Stephen Sprunk

I've a few questions concerning style when programming C on UNIX
systems. I don't want to look like an amateur. :)

The biggest mistakes that newbies make are lack of consistency and
trying to change others' style. If you're contributing to an existing
project, follow whatever established style it has, period.

If you're starting a new project, pick one of the common styles in other
projects you've seen and like. Do not modify (or "customize") the style
unless you can competently explain _why_ it does things the way it does
and you can demonstrate (to people more skilled than you) that your
change is an improvement for your particular project.

Do not invent your own style.
1. Having been programming in higher level languages for the last 15
years, I'm finding it hard to get used to DEFINES in all capitals. Is it
really frowned on not to do so? Is CamelCase acceptable?

EG. '#define MaxNumFiles 1024' not '#define MAXNUMFILES 1024'.

This is canonical and is done in all of the various styles I've seen.
There are very good reasons for that.

(It's more important for function-like macros, where you may need to
warn the user that arguments may be evaluated multiple times. OTOH,
function-like macros that mask a true function must use the case of the
function they mask, but must take care not to do multiple evaluation.)
2. My personal variable and function naming style is camel case, with
variable names beginning with a lower case char and function names not.
Is that acceptable, if not what is?

EG:
Variables: int numFiles = 0;

This is camelCase.
Functions: int CountNumFilesInDir(char* path);

This is PascalCase.

Mixing the two in the same project will drive adherents of _both_ styles
nuts. Pick one and stick to it; that way you'll only drive half of your
readers nuts.

(There's also this_type_of_identifier; the same logic applies, i.e.
don't mix that with either of the above. Never, never create some
God-awful hybrid with both underscores and uppercase letters...)

Some mixing is unavoidable if you call libraries that use different
styles, but don't deliberately make it worse.
3. Is there an accepted maximum line length? I've got a 24" monitor, if
I reach 120 chars I start thinking this might not look great in someone
else's editor.

Do not go over 80 columns without a very, very good reason.

If that presents a serious problem (i.e. more than the occasional
complicated function call or if expression), there's probably something
wrong with your code anyway.
4. Does anyone care where the pointer * is? I prefer keeping to next to
the type, rather than next to the variable name.

EG. I like: char* firstName; and not so much: char *firstName;

The latter is canonical in all styles. If you use the former, one day
you'll write "char* firstName, lastName;" and cause all sorts of problems.
5. On a slightly different note, I've been handling my error messages by
using #define string constants in a header file. I saw some code which
did this and it looked good to me. Is that standard practise, if not
what is?

EG. #define ErrorDirNotFound "The directory was not found."

Either put the string inline or use some facility such as gettext(),
which is better for later i18n issues anyway.
There are so many style guides out there, most of them say contradictory
things at one point or another. What do the pros do?

See comments at top.
Finally, before someone points this out... I know if I'm coding for
myself, and not following somebody else's stylistic requirements, I can
do whatever I want. However I'd like my code to be 'acceptable looking'
to the wider UNIX C community.

If your code will be read by someone else, you want the style to seem
familiar enough to them that it won't distract them from being able to
read what the code _means_; that generally means picking one of the
common styles even if it's not ideal according to your tastes.

If you're absolutely sure _nobody_ will _ever_ read your code, do
whatever you want--but I'd recommend picking a common style anyway just
in case you're wrong. People usually are about such things, eventually.

S
 
K

Keith Thompson

Stephen Sprunk said:
On 24 Feb 2010 12:35, Poster Matt wrote: [...]
EG:
Variables: int numFiles = 0;

This is camelCase.
Functions: int CountNumFilesInDir(char* path);

This is PascalCase.

Mixing the two in the same project will drive adherents of _both_ styles
nuts. Pick one and stick to it; that way you'll only drive half of your
readers nuts.

His convention apparently is to use camelCase for variables and
PascalCase for functions. It's not necessarily a style I'd use, but
it's not obviously horrible (and it's more or less the style I use
at work). As with most of these rules, conforming to existing code
is far more important than any benefits of one style over another.
I really dislike the brace placement of the code I work on, but
mixing my own style into it would be far worse (and wouldn't survive
a code review anyway).
(There's also this_type_of_identifier; the same logic applies, i.e.
don't mix that with either of the above. Never, never create some
God-awful hybrid with both underscores and uppercase letters...)

Again, This_Type_Of_Identifier isn't obviously horrible. (I use it
myself, though not in C.)

[...]
 
W

William Hughes

I would like to add that, as long as you're trying to use good style,
for God's sake don't use the wrong indentation style.  If you put your
opening braces on the same line as your conditional, you'll just look
like a fool in front of your friends and colleagues.

You need to fix your misprint. Clearly you meant

If you *dont* put your opening braces on
the same line as your conditional, you'll
just look like a fool in front of your
friends and colleagues.

- William Hughes
 

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

Members online

No members online now.

Forum statistics

Threads
473,995
Messages
2,570,230
Members
46,819
Latest member
masterdaster

Latest Threads

Top