Guide to Common Standards

Pages: 123
Currently under-construction.

INTRODUCTION
What is a set of standards and why am I reading this?
The purpose of C++ standards is to define a C++ coding standard that should be adhered to when writing code. ISO 9000 and the Capability Maturity Model (CMM) state that coding standards are mandatory for any organization with quality goals. Standards provide indications aimed at helping programmers to meet the following requirements on a program:
1.be free of common types of errors
2.be maintainable by different programmers
3.be easy to read and understand
4.have a consistent style


There are no hard and fast rules when it comes to programming style only the restrictions enforced by the compiler, however it is important to be consistent. Below we are going to touch on some of the styles and guidelines that should be followed as much as possible but without trying to enforce any concrete rules.

Most large companies have a set of standards that are enforced. If you are working for such a company you are being paid to write code subject based on what they want you to write, and in a style that must match up to their standards. The main reason being maintainability along with the above mentioned points.

People should also note that no standard should be followed to the letter, in fact most standards will have clauses that allow you to disregard certain points or have a priority listing(should, would, will). While you may be thinking that some of the standards you have seen seem completely silly, they do not always need to be followed, some can be disregarded and you can even create your own rules if the current project calls for such workarounds.

This will be at most a style guide, used to develop your own style but while still conforming to the needs of the community. It will cover 3 main topics: Naming, Style and Coding.

For a very in depth collection of styles and techniques Bjarne Stroustrup's C++ Style and Technique FAQ is a very good read: http://www2.research.att.com/~bs/bs_faq2.html

NAMING

Names are the heart of programming. In the past people believed knowing
someone’s true name gave them magical power over that person. If you can
think up the true name for something, you give yourself and the people coming
after power over the code. Don’t laugh!


1. Naming of files.
The names of header and implementation files are generally the same with different suffix file type, they are also commonly named the same as the class. Some operating systems are non-case sensitive while others are case sensitive so for cross compatibility reasons you should stick to one style of case naming, most programmers stick to lowercase file-names to avoid confusion.

other examples?

2. Naming of Classes, Functions, Variables, Constants, and Methods.
Meaningful names are important, recall the above statement about power over a name.
Usually functions and methods perform some type of action so naming the function in a way that describes what the function is doing is generally the best approach e.g.
WriteDataToFile( ) rather than DataFile( )
Classes are often nouns. By making function names verbs and following other naming conventions programs can be read more naturally. Make every variable name descriptive, limit the use of abbreviations or letter-words. It’s worth writing words completely since it makes the code much more readable. Beware however that when trying to find a good name, you don’t end up with with something like ’the_variable_for_the_loop’, use a proper English word for it like counter’ or ’iterator’, but with a prefix attatched to be more descriptive like 'appleCounter'. English is a rich language and trying to find a correctly fitting word is important for code readability, cleanness and variation. Whenever in doubt, just use a thesaurus.

Suffixes are sometimes useful:
• Max - to mean the maximum value something can have.
• Cnt - the current count of a running count variable.
• Key - key value.
For example: RetryMax to mean the maximum number of retries, RetryCnt to mean the current retry count.
• Prefixes are sometimes useful:
• Is - to ask a question about something. Whenever someone sees Is they will know it’s a question.
• Get - get a value.
• Set - set a value.
For example: GetMaxOrangeCnt( )

Some standard variables are used for often recurring tasks. Below is a list of those that are accepted (for those that follow the first, are used as a backup within the same scope) :
i , j , k : integer counter (used in for loops)
x, y, z : multiplication, or graph points.
r , c , d , t : row, column, depth, time (used for array/pointer cells)
it : STL-like iterator
c : char (temporary)
<type>_it : STL-like iterator of a certain type for differentiation amongst types
tmp_<type> : eg. tmp_qstring, tmp_int, tmp_float for variables that are solely used for the storage of temporary intermediate values
Notice the above I have listed both 'c' for column and 'c' for char, using both of these in the same scope would be a compilation error.
C++ is a case sensitive language so sometimes it may be tempting to use the same name for a variable with only a change in a case. This is generally considered poor practise as it becomes difficult to read and debug. e.g.
1
2
3
unsigned int truck;
unsigned double trucK;
const char Truck='T'; 

However another acceptable way of naming global members is with a 'g' or global constants with a 'gc' as a prefix, also the underscore is commonly used as a global identifier. e.g.
1
2
3
4
5
6
7
8
// header
private:
   int _balance; // member that stores balance of ones account
   // or
   int gBalance;
   // or
   int g_balance;
}; 

Additionally Hungarian notation can be used and combined with descriptive English names. For more information see this link: http://en.wikipedia.org/wiki/Hungarian_notation

For output of units of information, b for bits, B for bytes, and o for octets. SI prefixes are mostly used capitalized (K instead of k). If the prefix is a power of two, an i is added to it (KiB instead of KB). Otherwise, the prefix is a power of ten. The user should be aware of this difference where appropriate.
Last edited on
coming soon.
Last edited on
It's generally all pretty sound advise, but I have a few beefs with it:




NF1: I've heard that you should stick to lowercase filenames to avoid #include problems on platforms that are case sensitive. If the file is LostDog.h, then #include "lostdog.h" will compile on Windows, but will give you an error when you try to compile on *nix.

It also avoids the possibility of names that differ only by case. IE: "LostDog.h" and "lostdog.h" are 2 different files on *nix, but if you move to Windows, you'll have to rename one of them.

I stand by that.

NC3,4,5: All personal preference. I prefer ALLCAPSFORCONSTANTS, CapitalForFunctions, lowercaseforlocals, and nHungarianForMembers.

It doesn't matter what you use as long as you're consistent about it. If you're on a group project then you should do what everyone else is doing.


CB1: This rule gets abused all the time. There's nothing wrong with public members if they're not sensitive to the internal state of the object.

CB7: Eh. I see what he's trying to say there and I partially agree. Sometimes a design calls for two or more friend classes though. But granted it's not very often.

SG8: wtf? I don't do that personally, but why would that be a problem?
Last edited on
CL5: I would say that this rule should only extend to mixing pointers/non-pointers.
I'm not taking 40 lines to write out a bunch of integers when I could put them all on one line.

NF1, NC3-5: My opinion: Do it the way everyone else on your project is.

CB1: What if I have a POD class?

CF5: Mostly agreed, but if I'm in a 5 loop deep area, I'm going to use a goto to get out.

CO2: I kind of disagree here, I know that they are trying to reduce excess code compiling, but it would seem dumb to me to have to hope/require that one of the headers you are including includes std::string or whatever.
firedraco: good point about CO2

actually now that I read CO2 a little closer, it seems to directly contradict CO1. In order for a header to be fully self contained (which is good), you will need to #include some things. Things which are possibly already included in another header you're including.

+1 for sticking to "the right way". XD
closed account (z05DSL3A)
gcampton wrote:
The purpose of this post is to highlight common misused standards according to the C++ Coding Standard Version 1.1 issue: 5. By CERN-UCO.

Am I missing something, to me this sounds like here is a list of standards that are used but shouldn't be.

I'll have to go away and find this CERN-UCO C++ Coding Standard...

Edit:
http://pst.web.cern.ch/PST/HandBookWorkBook/Handbook/Programming/CodingStandard/c++standard.pdf
Last edited on
Hmm now I'm unsure the best way to go about this, really I just wanted something to point to that was relatively short and made sense.
Perhaps we should define our own set based on a number of different references or something?
Ok I have re-written everything for the above points and also some notes, also renamed the points and deleted a few. Also have included no references. Comments?
Last edited on
closed account (S6k9GNh0)
http://geosoft.no/development/cppstyle.html

I find this a bit more readable and it gives more reason as to why to follow it.
That geosoft link is not really a C++ guy giving pointers on good C++ style.

He is TOTALLY a Java guy trying to bring his Java convensions into C++.

Most of his points are fine, but there were a bunch I thought were strange and/or bad:

11. Private class variables should have underscore suffix.


I agree that members and locals should have some difference in how they're named, but I just never liked underscores... *shrug*

13. All names should be written in English.


That makes perfect sense.... if you're a native English speaker.

IMO it doesn't make much sense to have a program written with English code, when all the comments and documentation is in French or something.

And it certainly isn't reasonable to expect comments/documentation to be written in English only. That'd just be absurd.

The world doesn't revolve around English speakers.

23. The prefix n should be used for variables representing a number of objects.


The examples it shows for this are nPoints, nLines... which:

a) contradicts rule 22 (use plural for containers)
b) looks more like hungarian notation than just an 'n' prefix
c) contradicts rule 28 (don't abbreviate)

9. Abbreviations and acronyms must not be uppercase when used as name [4].


I think this one is just plain silly. You never mix case for acronyms. "Dvd"? "Html"? Come on. That's just begging for the var name to be typo'd repeatedly. But I guess that's not a problem if you have autocomplete.

29. Naming pointers specifically should be avoided.


Considering pointers have significantly different syntax from other variable types, I feel a distictions should be made. I always try to make a point to distinguish between pointers and nonpointers.

34. C++ header files should have the extension .h (preferred) or .hpp. Source files can have the extension .c++ (recommended), .C, .cc or .cpp.


.c++ is recommended? I've never seen that ever.

And really? recommending non alphanumeric characters in filenames? He's serious?

36. All definitions should reside in source files.


Right. Make it impossible to inline anything. That's great advice.

37. File content must be kept within 80 columns.


*choke*

What is this, 1996? 80 columns only takes up a 3rd of my screen.

How can you advocate this and long variable names + no abbreviations? They're almost mutally exclusive.

49. Class variables should never be declared public.


DIE DIE DIE. I hate this rule.

There's nothing wrong with public members as long as they don't reflect or impact the internal state of the object. People who follow this rule always end up wasting their time writing hundreds of pointless get/set functions that do nothing but sidestep the protection.

53. Implicit test for 0 should not be used other than for boolean variables and pointers.


Meh. That's a Java thing. if(myptr) is plenty clear. And all the more reason why you should distinguish between pointers and nonpointers (see my response to rule 29)

71. Basic indentation should be 2.


Pfft. Yeah... no wonder you limit yourself to 80 char width.

83. The function return type can be put in the left column immediately above the function name.

His example:
1
2
void
MyClass::myMethod(void) 

ew @ having the return type on it's own line
ew @ putting (void) in the parameter list

91. All comments should be written in English [2].


Hoic...
forget what I said about rule 13, apparently. He really does expect everyone in the world to speak English.

92. Use // for all comments, including multi-line comments.


I kind of see why he's saying that. I mean 2 or 3 lines or something, yeah. But for block comments it really does make more sense to use /* block comments */

11. No issues with that, it's a PERSONAL style thing though, you shouldn't try to force others to do it >_>

13. HAHAHA!

23. No. Name the variable what it is, and then you don't need weird crap like that.

9. Uh-huh, and the next thing you are going to tell me is that I can't use _ anywhere? Or that I MUST write out all numbers?

29. I personally don't name pointers specially, but it could help if you have lots of similar things (i.e. pointers to an object/normal objects in the same scope)

34. Wat? .c++????

5. Naming with a method is better?? Since when...?

17. No. No no no no NO.

20. Wat? I use init all the time, DEAL WITH IT!

25. j/k are for nested loops only? Why would you care...really?

28. Yeah, whatever. What about DVD? Or HTML? Those are basically abbreviations.

33. Void functions I agree. Value returning functions, not really. Is he suggesting that we rename printf num_args_printed?

36. The point of classes is that the programmer shouldn't HAVE to go look for the implementation!

37. Whatever, they can increase their damn screen width.

57. ???? I could say the same things about fors/whiles

60. Because testing against true is better than 1 for some reason. I sort of agree with for(;;) (mainly because it makes no sense) but they are all easily recognized as infinites.

68. Uh, not it's not? It's illegal to do that in C++.

71. Anything from 2-6 is probably fine really.

72. Or you could be consistent and use the same style everywhere...

At least he had this in there to cover himself:
2. The rules can be violated if there are strong personal objections against them.


I have some strong personal objections against some of them!!

Some good stuff I did find:

15. Agreed!

35. Agree.

40. Yes.

69. YES! Goto is evil, but sometimes it is needed.

90. Heh. Good points there. Unless of course the tricky code is faster then the rewritten code, or your employer isn't paying you to rewrite stuff that works...
37. Whatever, they can increase their damn screen width.

What if they're reading it in Vi[m]? I don't think it's fair to say "increase your screen width," as an example, when I was installing Arch Linux I didn't have a GUI until I installed X and GNOME. It was a good thing I limited all my source files to ~80 chars per line, because to pass the time it took to download and install X.org and GNOME I was programming.

Anyway, I find code where each line is <=80 chars long more readable anyway. What's better, readable code or short code? Obviously the former.

One thing I don't agree with in terms of making sure people in terminal[-emulators] can read your code is making sure each function only uses up 24 lines. That's over the top...

Yep I agree with chris, but at the same time I don't think it should be enforced these days, I'm pretty positive VI has word wrap anyway, it's only the console(cmd line) that's the problem, things like cat, more / less etc would have problems. (but then I think it has word wrap too, depending on the shell)

I generally have all my code under this anyway, the only times it seems to go over is when I have a pile of nested loops. (I think once or twice)
Typically it happens far more often in java than C++ as java has longer commands, and dot notation which is used frequently unlike C/C++

Output statements which can be fixed by using a '\' + newline or just close off the commas and continue on the next line:

cout << " blah blah ....."
<< " more blahing...."
<< " will it end? "
<< endl;
or
cout << "blah blah .... \
more blahing .... \
will it end? "
<< endl;

Some good stuff I did find:
15. Agreed!
35. Agree.
40. Yes.
69. YES! Goto is evil, but sometimes it is needed.

amazing you found 4 good ones! lolol

I was going to add 40 as it was in the original file I used, but figured it probably wasn't something that was misused all that often, I know gnu gives warnings so this was mostly presumption. Think it should be included ? and 15 ?
35, 69 already in there... and I updated 69(CF3) again to better reflect where it is useful.

1
2
15. The name of the object is implicit, and should be avoided in a method name. 
40. Header files must contain an include guard. 
Last edited on
a pile of nested loops. (I think once or twice)

A good rule of thumb is to not go over three levels of indentation.
Example:
1
2
3
4
5
6
7
8
9
10
11
12
    if (x == y) {
        /* Level one */
        if (x % y == 0) {
            /* Level two */
            if (x + y == 0) {
                /* Level three */
                if (x - y == 0) {
                    /* BAD */
                }
            }
        }
    }
Last edited on
What if they're reading it in Vi[m]?


Then they're dumb.

No offense, but if you're using an editor incapable of showing more than 80 characters, then you're using a stupid editor. It's 2010 for crying out loud. This hasn't been a problem for over 15 years.

when I was installing Arch Linux I didn't have a GUI until I installed X and GNOME. It was a good thing I limited all my source files to ~80 chars per line, because to pass the time it took to download and install X.org and GNOME I was programming.


That's your own fault for starting to use an OS before it was ready to use. Next time download everything before you start using it.

I could go on about how programs shouldn't use sound because I once tried to use my computer without speakers, but that would be absurd.

Anyway, I find code where each line is <=80 chars long more readable anyway.


I don't see how it makes any difference. *shrug*

Only problem with long lines is if they make you have to scroll the window. Which I agree is bad. But 80 columns is a little extreme.

A good rule of thumb is to not go over three levels of indentation.


I somewhat agree in that if you have that much indentation you probably should reorganize your code. That much nested anything is pretty fugly.

But just stopping indentation because you're reached the 3 indent count is a bad idea. Indentation doesn't get any less important. If anything it gets more important.


Output statements which can be fixed by using a '\' + newline or just close off the commas and continue on the next line:


Blech. Then you have to make sure there's no whitespace after the \ character. AND you can't have any indentation on the following line because it'll be counted as part of the string.

If it comes to that you can just concatenate strings... or just throw in another << operator. The \ thing is kind of ridiculous:

1
2
3
4
5
6
7
8
9
10
11
12
    cout << "This kills indentation \
and is fugly";

    cout << "This is"
            "way better";

    cout << "This is"
         << "even better";

    cout << "Or you could just";
    cout << "type 'cout' again";
    cout << "it's not like it's a big deal.";
Last edited on
I happen to write all of my code in Vim. It's a preference--just as nearly everything else mentioned in this thread.
Last edited on
That's your own fault for starting to use an OS before it was ready to use. Next time download everything before you start using it.

What? It was ready to use. I just didn't have a GUI.
How can I download everything without using it? What, am I meant to use windows to download the source code for GNOME and X, then set up a cross-compiler, compile the sources for Linux, move them to the /usr/bin directory (which can't be done in windows anyway, AFAIK there's no Ext3 driver (there is a [third-party] ext2 one)) and then reboot into Arch and log in? When I could just use the package manager from the command line, and use Vim to program while I'm bored?

I could go on about how programs shouldn't use sound because I once tried to use my computer without speakers, but that would be absurd.

That has no relevance whatsoever. And besides, as I said, restricting your code to 80 chars per line is much neater than having 400 char lines...

But just stopping indentation because you're reached the 3 indent count is a bad idea. Indentation doesn't get any less important. If anything it gets more important.

*shrug*, like I said, rule of thumb.

@Disch,
I agree about the backslash-newline stuff. That looks really horrible. Personally, I use
1
2
std::cout << "Line one.\n"
         << "Line two.\n";


For long macros I use backslash-newline, but I never escape the newline in a string-literal because you end up with
a) retarded looking code
b) retarded looking output;
e.g.
1
2
std::cout << "Here's some text that I think is too long to fit on one line; \
so I'm going to escape the newline and make my code look retarded.\n";

Here's some text that I think is too long to fit on one line; so I'm going to escape the newline and make my code look retarded

or
1
2
std::cout << "Here's some text that I think is too long to fit on one line;\
              so I'm going to escape the newline and make my output look retarded.\n";

Here's some text that I think is too long to fit on one line;              so I'm going to escape the newline and make my output look retarded.
Last edited on
closed account (S6k9GNh0)
Well, I liked _most_ of them. I didn't read all of it since it followed a majority of what it does.

1) You've really never seen a project with .c++ extension? Though I don't think it's right, I've seen a few small projects that have done this. I always figured it was preference. It really doesn't matter...

2) When people use set and get functions, it's for a level of abstraction. It's to make sure that the person who needs the variable is getting the variable correctly and how the library meant for them to receive the variable. Most professional libraries and non-professional libraries do this. This is especially for set functions in case something else needs to be done, now that the variable is set. Most of the time, you can setup a small shortcut to the variable using a reference or pointer. There is usually no visual affect on the library user nor is there a performance hit for something so easily maintainable.

3) I don't agree with his concept of the do - while loop. I find that completely wrong.

4) For number 68, he was referring to older C++ where int would be returned if nothing else was specified. getValue() {} // This actually has a return type of int in historic C++ . They've changed this of course but no reason to take it off from what I can see.

5) For number 33, his saying to make sure the user can tell what the function does, just by its name. printf is fine because it prints to a file stream and I can understand that. printf could be a void function by all means since the user normally doesn't rely on the return value.
Last edited on
What? It was ready to use. I just didn't have a GUI.


*scratches head*

I guess that somehow makes sense to you. Personally I find that mind boggling.

How can I download everything without using it?


The same way you downloaded Arch Linux, maybe?

Download everything from a fully functioning computer, burn it to a disc or something, then install it all in one go.

What, am I meant to use windows to download the source code for GNOME and X, then set up a cross-compiler, compile the sources for Linux


Oh crap. You do the whole "recompile everything" thing.

We're just in two different worlds I guess.

In my world:
- I'm never stuck using the terminal as a text editor, or any other "text editor" that lacks a GUI.
- I have a respectable screen resolution
- There's never any problem viewing text that is wider than 80 columns in any text editing program

You apparently don't live in my world.

That has no relevance whatsoever


Tit for tat. You gave an absurd situtation involving a not-quite-complete computer where less than 80 columns was necessary.

I was trying to point out how absurd it was by giving an equally absurd situation involving a not-quite-complete computer.


Anyway I feel this thread degenerating. Perhaps I should just drop it. XD


2) When people use set and get functions, it's for a level of abstraction.


This makes sense if there's abstraction/encapsulation going on.

The problem with the "always make members private" rule is that some members really don't need to be private.

Stuff like this:

http://www.cplusplus.com/forum/general/18608/

There is no reason for those get/set members other than to make the programmer's life miserable.

Don't get me wrong -- I understand what the rule is trying to go for, and I agree with the concept. But this rule gets overly abused all the time.
Oh crap. You do the whole "recompile everything" thing.

No, I use the package manager. That was my point. The only way I could have possibly installed those programs without using the package manager would be to cross-compile them from source. You don't download an installer with Linux, you use the package manager. It's alot quicker when you get used to it; I can just pacman -S <package> and it will install it for me. Most of the packages are named logically, so I can guess. If not, I just google it. It's alot easier than running a web browser, finding some obscure website that hosts the file I need, downloading the installer and waiting for it to install, even if I do need to google the package name.

- I'm never stuck using the terminal as a text editor, or any other "text editor" that lacks a GUI.

Vi[m] is a VIsual editor, it has an ncurses "GUI". Now, Vi[m] isn't the easiest editor to use, and I'm inexperienced with it, so I'm slow with it. Because of that, if I need to use the command-line for any reason, I use GNU Nano, which is about the easiest text editor to use there is. It also has an excellent method of handling >80-char lines (it prints a $ instead of the missing characters, and you traverse the line until you can read them, and then you go back).

- I have a respectable screen resolution

1440x900x32, 16:10, 75 Hz is good enough for me.

- There's never any problem viewing text that is wider than 80 columns in any text editing program

I don't have a problem viewing it. I'm saying that it looks neater, and it's better for people who wish to use Vi[m] (Vi and Vim are extremely fast and powerful in the hands of a sufficiently experienced user. I can say that having watched this guy writing Java in Vim).
Last edited on
Pages: 123