Coding Conventions

Pages: 12
closed account (oE6pX9L8)
Hi guys,

I'm archmage84, and I love the tutorial on this page. It's really helped me learn how to do stuff well.

I'm a little curious as to the conventions that people use when coding.I seem to recall reading somewhere that copypasting source code is frowned upon here, so I won't do it unless someone confirms otherwise (I don't want to seem like yet another programming noob).

From what I've heard, generally spacing out is a good thing, right?

I'd just like to get a few opinions on how to lay out code, to increase my skills. Thanks.

archmage84
Hi archmage84,

Yes, it is generally a good idea to space out your code. It is also a great idea to comment your code by using two backslashes ("//") so you can better understand your code. Another thing i would recommend, line up the bodies of your if-else statements and loops, especially if they are nested.
We might also recommend using comments that begin with /* and end with */ for multiple-line comments.

I would also recommend spreading larger programs over multiple functions.

This is not really a coding convention, but in this forum, we request that you use [code] tags. You'll see why when you use 'em. ;)

There are a few features of C++ that most members of this forum absolutely hate, and while I use them in my code on a regular basis, I can see why they're generally hated. First of all, most of us dislike system(), for reasons that may be found in the stickied post in the Articles section. Second, most of us dislike recursion (calling a function from within itself), for the simple reason that one slip-up and you get a buffer overflow. Third, most of us will tell you to never use the type void*. It effectively bypasses all the compiler's type checking, and is VERY easy to mess up. The list is longer, but those are at the top of it. When someone says that something is "illegal" or "evil" and yet it compiles just fine, it's part of that list.


Welcome!

-Albatross
Last edited on
closed account (oE6pX9L8)
Thanks, I'm fairly fussy with my code. Do you mind if I include a small program? Here it is:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
// Program to refine use of void and prototype functions.

#include<iostream>
#include<string>

using namespace std;

string CHOICE;
int COUNTER = 1;

void Starline(int STAR_COUNT, int WHITESPACE, int PRE_ENDL, int POST_ENDL);

/* Variable order:
   number of stars, number of spaces before, lines before, lines after. */

int main(void)
{
 Starline(79, 0, 0, 1);
 cout << " Test Program";
 Starline(79, 0, 1, 1);
 Starline(39, 20, 1, 2);
 cout << "Please hit Enter to exit.";
 getline(cin, CHOICE);
 return 0;
}

//Starline function defined here.

void Starline(int STAR_COUNT, int WHITESPACE, int PRE_ENDL, int POST_ENDL)
{
 for(COUNTER = 1; COUNTER <= PRE_ENDL; COUNTER++) cout << endl;
 for(COUNTER = 1; COUNTER <= WHITESPACE; COUNTER++) cout << " ";
 for(COUNTER = 1; COUNTER <= STAR_COUNT; COUNTER++) cout << "*";
 for(COUNTER = 1; COUNTER <= POST_ENDL; COUNTER++) cout << endl;
}


Would you be able to point to specific parts of this to comment on? Thanks.

archmage84

PS: Albatross, I like the [code] tags. They're pretty awesome!
@archmage84

Use whatever convention you are comfortable with.

I would say that it is better to be consistent with your coding style that choosing one style over another.

The important thing is that your code is easy to read. That is, after all, the only reason to format code a specific way. Its all the same to the compiler. It doesn't care.

So its about making your code understandable to other coders.

I would also suggest that people don't get 'precious' about their own particular coding standards. When modifying someone else's code, be prepared to use their coding style so that other readers will not be confused by your edits.

So, in short, I would say, keep it understandable and be flexible.

Personally my coding style has evolved over the years. When I see something done that is either clearer or safer than the way I currently do something, then I might incorporate it into my own methodology.
archmage84 wrote:
Would you be able to point to specific parts of this to comment on?


Sure, but this is not rules, just my personal ways:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
// Program to refine use of void and prototype functions.

#include<iostream> // I leave a space between the include and the <>
#include <string> // like this, but each to their own.

using namespace std; // I don't often use this.

/*
   Its bad to use the 'using namespace' this in header files but
   I also avoid it in cpp files as well. The main reason being that
   it can get confusing as to which class you are referring to.
   But obviously sometimes it really makes the code clearer. It is good
   to remember that you can use that in a single function so as not to
   pollute the whole file.
*/

string CHOICE; // personally I tend to reserve CAPS for macro definitions.
int COUNTER = 1;

/*
   I personally only use Caps at the beginning of an identifier for class declarations.
   But it seems to be fairly common to use them for function declarations as you
   have in the Microsoft world.
*/
void Starline(int STAR_COUNT, int WHITESPACE, int PRE_ENDL, int POST_ENDL);

/* Variable order:
   number of stars, number of spaces before, lines before, lines after. */

// I never explicitly use void in this context. Not since the days when C demanded it :)
int main(void)
{
 /*
   I have religiously used tabs and religiously set my tab spacing to 4 characters.
   That seems most common but I have seen people set to 8 character spacing.
   I have hardly ever seen anyone use spaces rather than tabs.
 */
 Starline(79, 0, 0, 1);
 cout << " Test Program";
 Starline(79, 0, 1, 1);
 Starline(39, 20, 1, 2);
 cout << "Please hit Enter to exit.";
 getline(cin, CHOICE);
 return 0;
}

//Starline function defined here.

void Starline(int STAR_COUNT, int WHITESPACE, int PRE_ENDL, int POST_ENDL)
{
 for(COUNTER = 1; COUNTER <= PRE_ENDL; COUNTER++) cout << endl;
 for(COUNTER = 1; COUNTER <= WHITESPACE; COUNTER++) cout << " ";
 for(COUNTER = 1; COUNTER <= STAR_COUNT; COUNTER++) cout << "*";
 for(COUNTER = 1; COUNTER <= POST_ENDL; COUNTER++) cout << endl;
}
/*
  I recently changed from using post increment to pre increment in my for loops like this:
*/

   for(size_t i = 0; i < vec.size(); ++i);

/*
   I also use size_t in preference to int when I am using unsigned integers like
   for accessing an array or something similar.
*/


But I like your code. Its well readable and very clear. It is good that you are fussy with your code because that will lead you to be consistent. That will help people to become familiar with your style more quickly!
Last edited on
I usually follow combination of C++ and Java's naming convention but with some edits, and I combine K&R and Allman style for my indents.

http://en.wikipedia.org/wiki/Naming_convention_%28programming%29#C_and_C.2B.2B_languages
http://en.wikipedia.org/wiki/Indent_style#K.26R_style
http://en.wikipedia.org/wiki/Indent_style#Allman_style_.28bsd_in_Emacs.29


[edit]

I suggest the coding style of m4ster r0shi
http://www.cplusplus.com/forum/lounge/22760/#msg119685
Last edited on
Galik +1

Don't get too fussy about pre/post increment with machine/integer values. They do the same thing equally well. (That is, unless you have a bad compiler, there shouldn't be any performance penalty.)

Personally, I cannot stand tabs because everyone has them set at something weird -- or, almost as bad, left at eight spaces. I always use just two spaces. I have recently learned that three spaces is also common (which I think is an odd number), as is four.

I've even had to go as far as to write a little program to demangle other people's code because of inconsistent spacing with tabs -- just to make it readable.

In C++, int main(void) was never valid. It is only tolerated by compilers because of C99. IIRC.
closed account (oE6pX9L8)
@Galik: For #includes, I think a space looks nicer. I tried using it without a space, but it just doesn't look right.

To clarify a few things, I programmed in Python originally, as my first language. C++ is quite different, but I've retained a few things. I only use one space because it's really neat, and is also easy to tell which level of nesting a line is in.

I found that VARIABLES, Functions and other words works for me, as I don't get confused when I see something.

You mentioned something about using namespace std;. I'm still fairly inexperienced, so why don't you need to include it?

I included the void in int main() as another trial change to my style. I don't think I like it, in hindsight, so it won't be happening again.

The way you specified your for loops is fine, but I prefer mine.

@Duoas: Thanks for the advice.

archmage84
archmage84 wrote:
You mentioned something about using namespace std;. I'm still fairly inexperienced, so why don't you need to include it?


Instead of including using namespace std; you can simply prefix every class, or type from the std namespace like this:

1
2
3
4
5
6
#include <string>
#include <vector>

std::string str;

std::vector<std::string> vec;


It is essential to do this in public header files and preferable in source files as well.

http://www.parashift.com/c++-faq-lite/coding-standards.html#faq-27.5

Inside your cpp files it is perfectly fine to use using namespace x, so long as you pay attention to what is being included.

In header files it is Bad.
http://www.cplusplus.com/forum/beginner/5871/#msg26251
http://www.cplusplus.com/forum/beginner/19931/
http://www.cplusplus.com/forum/beginner/14325/#msg70048

Hope this helps.
closed account (oE6pX9L8)
Sorry, the links didn't help. I'm an inexperienced programmer; I don't even get what using namespace DOES :(

But as long as it's fine to use it in single programs without headers, then I'm cool with it.

Thanks,
archmage84
What using namespace std; basically does in this case, is to allow you to use the functions/classes from the standard library-ish... (std = standard)

So, without using namespace std;

Your code would have to look something like this:
1
2
3
std::cout << "Hello, i now have to prefix every cout, cin and alot of other stuff.\n";
std::string = "Yo.";
std::cout << yo;


But when you are using the std namespace, it simply relieves you of the task to prefix every function you want to use out of that library/whatever-it's-called, so instead you can write:

1
2
3
4
5
using namespace std;

cout << "Hello, i now no longer have to prefix most functions, aint this a bit easier?\n";
string = "Yo.";
cout << yo;


So basically, just by adding that little line at the top of your program, you don't have to prefix all those functions you're going to use. You can see the difference in those two code snippets above, and of course decide yourself which you prefer to use.
Another alternative is to declare each item you wish to use individually from the namespace:

1
2
3
4
using std::cout;
using std::endl;
using std::vector;
using std::string;


This has the benefit of documenting where each type comes from at the top of your source file (.cpp) without dragging hundreds of names into the global namespace that may cause unexpected side effects.

Once again, this should only be done in source files (.cpp) but not header files (.h)
Last edited on
Including whole namespaces in a programme violates the purpose for what a namespace was created for in the first place! So if u are sure it's the only utilities you are gonna use I mean from that namespace it's ok but I tend not to be that lazy and write things by their qualified names...

About conventions along the way you'll see things that will seem to you like best suited and then u'll change from one to the other.

@Galik I agree...

Find ur own and be consistent with it!

COUNTER should definitely not exist globally. You should declare variables as locally as possible. So in this case, inside the for statement. The same thing applies to CHOICE.
It is very unusual to actually name a counter variable COUNTER. Instead lower case letters are used (usually i and j, k, l ... for nested inner loops)
@Duoas,
I disagree on tabs. The traditional tabsize is 8 spaces; if you set it to something other than that you're asking for bad indentation.

I also dislike indentation of < 4 spaces; I think it makes code easier to read with a big indent (but not bigger than 8 spaces). Also, 8 is an integral, positive multiple of 8 which is good.

@OP,
I pretty much follow the Linux kernel coding standards, which would be K&R, 8 space tabs for indents, all lowercase variable names, all uppercase macro names (except for macro functions -- I like to pretend they're normal functions so I name them in lower case). The only indentation styles I like are K&R (because it was the style used in the first official book about C) and Allman (aka ANSI style, because ANSI documentation always uses that style), although I don't have any issues with others (except the GNU style, which I find virtually illegible).

As has already been said: find a style and stick with it, be it K&R or ANSI/Allman or anything.
Last edited on
I know full well that the traditional tabsize is eight spaces. All my tools are normally set to use eight-space tabs.

The problem is that significantly many programmers set their tabs to things like 2, 3, and 4 spaces for writing their programs. Whether or not you like it doesn't change the fact that it happens, and with distressing regularity.

Choice of space count is personal preference. I prefer two spaces. You prefer four.

Straw man bothers me. My argument was: I don't like tabs because they are misused; use spaces instead.
I actually prefer 8 spaces to 4; I think 4 is the minimum that should be used. I have no issue with two, I just think four is better and 8 is even better than 4.

I also think only numbers that can make 80 should be used for indentation; preferably even numbers (but 5 is the only odd number that can make 80 anyway, which is ok).
closed account (Lv0f92yv)
If I may jump in,

Second, most of us dislike recursion (calling a function from within itself), for the simple reason that one slip-up and you get a buffer overflow.


Aren't there some solutions (things like searching, data structure traversal, etc) where a recursive solution is more straightforward to write (and read) than an iterative one? I know there is a formula for switching from one to the other (and sometimes the optimizer for the compiler does this automatically?).

An iterative solution can turn into an infinite loop if not done correctly just as a recursive function can cause a stack overflow... What is the real demon with recursive functions - if you do them correctly, they can be easier to read and conceive than iterative solutions - for SOME problems?
Last edited on
Pages: 12