I am new to C++ and would like to know what style I should use to write my codes. For example, should I use:

for (int i=0; i < 10; ++i) {
  cout << i << endl;
}

or

for (int i=0; i < 10; i++)
{
    cout << i << endl;
}

That is, should I put the starting bracket on the next line, should I use ++i or i++, how many spaces should I indent, should I use tabs, etc?

Is there any standard C++ programmers follow?

Any help will be appreciated.

Thanks.

Yeah just reading it through a little more we come to this:

Block layout should be as illustrated in example 1 below (recommended) or example 2, and must not be as shown in example 3 [4]. Function and class blocks must use the block layout of example 2.

example 1:

while (!done) { 
   doSomething();
   done = moreToDo(); 
}

example 2

while (!done) 
{ 
    doSomething(); 
    done = moreToDo(); 
}

example 3 -- The wrong way

while (!done) 
    { 
        doSomething(); 
        done = moreToDo();
    }

So hopefully that clears it up! :)

Is there any standard C++ programmers follow?

are you need coding standards ?
yes there are .....http://www.possibility.com/Cpp/CppCodingStandard.html
But nobody is 100% using this as a rule , it's like nobody will read the entire documentation of the linux/unix.

The above link is about general C++ coding standard. There is a GNU coding standard as I knew ( used inside the Linux kernel ).

and in the windows projects mostely there is another style.

well my advice is use your own if you are not forced to do. If not
then use what they said to use. If you are working in a GNU project then the best is GNU coding standards.

Don't go to break it. instead use it.

>should I put the starting bracket on the next line
Whichever you find easier to read.

>should I use ++i or i++
For built-in types, it doesn't matter. For user-defined types, the prefix increment is preferred. If you have trouble remembering that guideline, always use the prefix form when the expression result isn't needed.

>how many spaces should I indent
Enough to differentiate levels of nesting but no so much that everything wraps or rolls off the side of the screen. Usually this means an indentation size of two to four (though eight is still somewhat common).

>should I use tabs
If you care about the precise formatting of your code, no. If you're okay with the text editor controlling how big each tab stop is, go for it. But if you choose tabs, don't mix tabs and spaces because it will screw up your code when you move to a different editor.

>Is there any standard C++ programmers follow?
Yes, there are a great many. Just pick something sensible and go with it. You're likely to change your style as you learn anyway.

This article has been dead for over six months. Start a new discussion instead.