views:

303

answers:

11

Hi all.

I come from a the Objective-C and Cocoa world where there are lots of conventions and many people will say it makes your code beautiful! Now programming in C++ I cannot find a good document like this one for C++.

http://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/CodingGuidelines/CodingGuidelines.html

Standard C++ probably does not have something like above but I hope I can stick to some other SDK or APIs (like Microsoft's(?),etc) conventions.

I hope you can provide me with some links.

Thanks.

Ignacio.

+2  A: 

While many people will suggest more or less strict Hungarian notation variants (scary!), for naming suggestions I'd suggest you take a look at Google C++ Coding Guidelines. This may well be not the most popular naming conventions, but at least it's fairly complete. Apart from sound naming conventions, there's some useful guidelines there, however much of it should be taken with a grain of salt (exception ban for example, and the tendency to keep away from modern C++ coding style).

Although personally I like the extreme low-tech convention style of STL and Boost ;).

Kornel Kisielewicz
Google's C++ Coding Guidelines are awful, do not adopt them. (Except anything as inconsequential as naming conventions.) The Google style guide is the antithesis of good modern C++ code.
GMan
@GMan: I agree, Google guidelines are meant specifically to be backward compatible with their existing C code base (as is mentioned explicitly in the guidelines). For a new project, they are one of the worst thing that could happen.
Matthieu M.
@GMan, that's what I initially thought too, but more careful study of the document made me realize that it strikes a good balance between leaving some room to breathe to pros and (more importantly) not allowing newbie developers to blow themselves up. You can't count on having a team of good modern C++ coders anywhere -- and even one bad coder can ruin a good codebase without strict guidelines...
Kornel Kisielewicz
@GMan: could you explicit what you find awful in the Google guidelines ? I'm reading it right now and some advices seem pretty good.
ereOn
I have not seen anybody seriously suggest Hungarian notation in twenty years. The only time it is mentioned is as the antitheses of what you should do. PS. You need to read the Google standard again (for any new project it should not be used unless you want backward compatibility with google's original code.).
Martin York
@ereOn: It says don't use exceptions. What do you think is good? I mean a lot of it is boilerplate. But when it deviates it deviates.
Martin York
@Martin, I agree that the exceptions clause is ridiculous ;)
Kornel Kisielewicz
@Martin York: Actually, I hadn't read that part yet... indeed, some advices are terrible. (And especially this one, yes) For what I found good, was all the "common-sense" advices regarding variable lifetime. But I realize it is not exactly specific to Google.
ereOn
@Kornel: Modern C++ doesn't mean hard C++.
GMan
@GMan, so do I think, but for the time I was working at a corporation coding in C++ it was next to impossible to enforce in any way Modern C++...
Kornel Kisielewicz
@Kornel: That is unfortunate. :(
GMan
A: 

not nearly as concise as the link you provided: but the following chapter 14 - 24 may help :) hehe

ref: http://www.amazon.com/Coding-Standards-Rules-Guidelines-Practices/dp/0321113586/ref=sr_1_1?ie=UTF8&s=books&qid=1284443869&sr=8-1-catcorr

alien052002
Just skimmed through it, and it's hardly anything about naming there (except the obvious_like_dont_do_too_long_and_useless_variable_names...)
Kornel Kisielewicz
doooh... you're right. i was thinking "structural" convention rather than naming convention because i wasn't trying to understand your question and reading the link you provided.
alien052002
hmm... couldn't downvote myself for idiocy. but you didn't down vote me, thanks.
alien052002
@alien052002, why should I? At least you linked to a really good book :>
Kornel Kisielewicz
This book is about elements of programming style that help to improve code quality, and irrelevant details like naming conventions are summed up in Item 0: Don't Sweat The Small Stuff (or: Know What Not To Standardise). It won't help if you feel the need to standardise the irrelevent details.
Mike Seymour
+2  A: 

To address the broader issue of style guides I suggest picking on and stickign to it. the Google style guide is very detail/comprhensive, so it a good choice.

A common convention just for naming is: camelCase for all names, (except constants)
Begining with a capital if it's a class.
lowercase if not.
Constants in ALL_CAPS with underscore seperating works.
functions can be written the same as veriables, camelCase (you can tell it's a function cos it requiere the () after it)
and member veribles prefixed with an m and thuse would be written mCamelCase

It's really up to you or alternitivly the people you work for/with or the university you study at.

For a detail look at a variety of styguides / rationals behind htem, check out the "Pragmatic Programmer" by Andrew Hunt and David Thomas

Oxinabox
Detailed does not imply good. Like I said on Kornel's answer, the GSC is awful. It only works for them because they had a huge amount of pre-existing C with Classes (i.e. bad C++) code. Modern C++ is better, and contradictory to the style guide.
GMan
.......variable
Alexander Rafferty
Actually, IMHO, Detail is close to good.If not the GSC, then find another detailed one, (that is good) and use that.The important thing is being consistant.And a detailed guide helps with that.So if the GSC is shcokingly aweful then, find another and stick to it.
Oxinabox
+4  A: 

Do whatever you want as long as its minimal, consistent, and doesn't break any rules.

Personally, I find the Boost style easiest; it matches the standard library (giving a uniform look to code) and is simple. I personally tack on m and p prefixes to members and parameters, respectively, giving:

#ifndef NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP
#define NAMESPACE_NAMES_THEN_PRIMARY_CLASS_OR_FUNCTION_THEN_HPP

#include <boost/headers/go/first>
#include <boost/in_alphabetical/order>
#include <then_standard_headers>
#include <in_alphabetical_order>

#include "then/any/detail/headers"
#include "in/alphabetical/order"
#include "then/any/remaining/headers/in"
// (you'll never guess)
#include "alphabetical/order/duh"

#define NAMESPACE_NAMES_THEN_MACRO_NAME(pMacroNames) ARE_ALL_CAPS

namespace lowercase_identifers
{
    class separated_by_underscores
    {
    public:
        void because_underscores_are() const
        {
            volatile int mostLikeSpaces = 0; // but local names are condensed

            while (!mostLikeSpaces)
                single_statements(); // don't need braces

            for (size_t i = 0; i < 100; ++i)
            {
                but_multiple(i);
                statements_do();
            }             
        }

        const complex_type& value() const
        {
            return mValue; // no conflict with value here
        }

        void value(const complex_type& pValue)
        {
            mValue = pValue ; // or here
        }

    protected:
        // the more public it is, the more important it is,
        // so order: public on top, then protected then private

        template <typename Template, typename Parameters>
        void are_upper_camel_case()
        {
            // gman was here                
        }

    private:
        complex_type mValue;
    };
}

#endif

That. (And like I've said in comments, do not adopt the Google Style Guide for your code, unless it's for something as inconsequential as naming convention.)

GMan
Hey! you sneak in your brace-style preference! Personally I much prefer to have braces even for one-line statements, it's easy to screw up the indentation (when people inadvertently edit with another tab/space settings) and braces make the scope evident so you don't wonder whether or not the following line was meant to belong to the block or not...
Matthieu M.
+1 : Yeah, that's the style I use in my own projects. INCLUDING the brace style preference ;)
Kornel Kisielewicz
Mine is similar. The only difference. Types start with an uppercase letter. Everything else starts with a lower case letter (just my quirk).
Martin York
@Martin, curiosity -- so types still use underscores and capitals? Class_name_like_this or Class_Name_Like_This?
Kornel Kisielewicz
@Matthieu: Ha, I wouldn't pass the opportunity up. :) I used to religiously defend having braces always, but nowadays I find it cleaner to omit them. (Typically the single statements are `return;` or something trivial).
GMan
@GMan: So do I when I am working alone, but when I have to share my work I prefer to be as explicit as possible, including for one-line blocks. However I do put them inline: `if (cond) { return xxx; }` if possible.
Matthieu M.
I agree with Matthieu. Always use braces!! When I was young and naïve I hated braces, which I thought cluttered up my codez. Now when I'm older and wiser I live by the rule to always make my intentions clear. Putting braces around one-liners is one part of doing just that.
Andreas Magnusson
I 've been looking for a document about Boost naming conventions and only could find this: http://www.boost.org/development/requirements.html Did you learn it by using it or maybe read something?
nacho4d
@Gman: for one-liners I prefer to keep the braces, and just put it on a single line, as Matthieu showed. It's even shorter, and it's explicit and I don't have to worry about messing up if I add another line to the body.
jalf
A: 

It really doesn't matter. Just make sure you name your variables and functions descriptively. Also be consistent.

Nowt worse than seeing code like this:

int anInt;                  // Great name for a variable there ...
int myVar = Func( anInt );  // And on this line a great name for a function and myVar
                            // lacks the consistency already, poorly, laid out! 

Edit: As pointed out by my commenter that consistency needs to be maintained across an entire team. As such it doesn't matter WHAT method you chose, as long as that consistency is maintained. There is no right or wrong method, however. Every team I've worked in has had different ideas and I've adapted to those.

Goz
It DOES matter. You talk like you'd never have worked in a team before.
Kornel Kisielewicz
Well it DOESN'T matter as long as its descriptive and consistent ... Yes in a team that means maintaining that consistency across a whole team. I will update my answer.
Goz
+8  A: 

There are probably as many naming conventions as there are individuals, the debate being as endless (and sterile) as to which brace style to use and so forth.

So I'll have 2 advices:

  • be consistent within a project
  • don't use reserved identifiers (anything with two underscores or beginning with an underscore followed by an uppercase letter)

The rest is up to you.

Matthieu M.
+1 for "be consistent"; that's the single most important rule of the lot (and the only one that you'll probably get everyone to agree with).
Donal Fellows
+1 reserved identifiers, just cos the compiler isnt using it now doesn't mean the next version won't
jk
+1  A: 

There are many different sytles/conventions that people use when coding C++. For example, some people prefer separating words using capitals (myVar or MyVar), or using underscores (my_var). Typically, variables that use underscores are in all lowercase (from my experience).
There is also a coding style called hungarian, which I believe is used by microsoft. I personally believe that it is a waste of time, but it may prove useful. This is were variable names are given short prefixes such as i, or f to hint the variables type. For example: int iVarname, char* strVarname.

It is accepted that you end a struct/class name with _t, to differentiate it from a variable name. E.g.:

class cat_t {
  ...
};

cat_t myCat;

It is also generally accepted to add a affix to indicate pointers, such as pVariable or variable_p.

In all, there really isn't any single standard, but many. The choices you make about naming your variables doesn't matter, so long as it is understandable, and above all, consistent. Consistency, consistency, CONSISTENCY! (try typing that thrice!)

And if all else fails, google it.

Alexander Rafferty
Naming **every** class with an ending '_t' would be downright evil...
Kornel Kisielewicz
It is used for classes used as data types.
Alexander Rafferty
@Alexander, which classes aren't?
Kornel Kisielewicz
+3  A: 

We follow the guidelines listed on this page: C++ Programming Style Guidelines


I'd also recommend you read The Elements of C++ Style by Misfeldt et al, which is quite an excellent book on this topic.

missingfaktor
+2  A: 

I actually often use Java style: PascalCase for type names, camelCase for functions and variables, CAPITAL_WORDS for preprocessor macros. I prefer that over the Boost/STL conventions because you don't have to suffix types with _type. E.g.

Size size();

instead of

size_type size();   // I don't like suffixes

This has the additional benefit that the StackOverflow code formatter recognizes Size as a type name ;-)

Philipp
A: 

consistency and readability (self-documenting code) are important. some clues (such as case) can and should be used to avoid collisions, and to indicate whether an instance is required.

one of the best practices i got into was the use of code formatters (astyle and uncrustify are 2 examples). code formatters can destroy your code formatting - configure the formatter, and let it do its job. seriously, forget about manual formatting and get into the practice of using them. they will save a ton of time.

as mentioned, be very descriptive with naming. also, be very specific with scoping (class types/data/namespaces/anonymous namespaces). in general, i really like much of java's common written form - that is a good reference and similar to c++.

as for specific appearance/naming, this is a small sample similar to what i use (variables/arguments are lowerCamel and this only demonstrates a portion of the language's features):

/** MYC_BEGIN_FILE_ID::FD_Directory_nanotimer_FN_nanotimer_hpp_::MYC_BEGIN_FILE_DIR::Directory/nanotimer::MYC_BEGIN_FILE_FILE::nanotimer.hpp::Copyright... */
#ifndef FD_Directory_nanotimer_FN_nanotimer_hpp_
#define FD_Directory_nanotimer_FN_nanotimer_hpp_

/* typical commentary omitted -- comments detail notations/conventions. also, no defines/macros other than header guards */

namespace NamespaceName {

/* types prefixed with 't_' */
class t_nanotimer : public t_base_timer {
    /* private types */
    class t_thing {
        /*...*/
    };
public:
    /* public types */
    typedef uint64_t t_nanosecond;

    /* factory initializers -- UpperCamel */
    t_nanotimer* WithFloat(const float& arg);
    /* public/protected class interface -- UpperCamel */
    static float Uptime();
protected:
    /* static class data -- UpperCamel -- accessors, if needed, use Get/Set prefix */
    static const t_spoke Spoke;
public:
    /* enums in interface are labeled as static class data */
    enum { Granularity = 4 };
public:
    /* construction/destruction -- always use proper initialization list */
    explicit t_nanotimer(t_init);
    explicit t_nanotimer(const float& arg);

    virtual ~t_nanotimer();

    /*
       public and protected instance methods -- lowercaseCamel()
       - booleans prefer is/has
       - accessors use the form: getVariable() setVariable().
       const-correctness is important
     */
    const void* address() const;
    virtual uint64_t hashCode() const;
protected:
    /* interfaces/implementation of base pure virtuals (assume this was pure virtual in t_base_timer) */
    virtual bool hasExpired() const;
private:
    /* private methods and private static data */
    void invalidate();
private:
    /*
       instance variables
       - i tend to use underscore suffix, but d_ (for example) is another good alternative
       - note redundancy in visibility
     */
    t_thing ivar_;
private:
    /* prohibited stuff */
    explicit t_nanotimer();
    explicit t_nanotimer(const int&);
};
} /* << NamespaceName */
/* i often add a multiple include else block here, preferring package-style inclusions */    
#endif /* MYC_END_FILE::FD_Directory_nanotimer_FN_nanotimer_hpp_ */
Justin
`_FD__Directory_nanotimer_FN__nanotimer_hpp_` is a reserved identifier.
GMan
@GMan thanks. updated.
Justin
@Justin: Now it's ever more reserved...you should read the [identifier rules](http://stackoverflow.com/questions/228783/what-are-the-rules-about-using-an-underscore-in-a-c-identifier).
GMan
@GMan it's been updated
Justin
@Justin: It still has double underscores. :X
GMan
A: 

For what it is worth, Bjarne Stroustrup, the original author of C++ has his own favorite style, described here: http://www2.research.att.com/~bs/bs_faq2.html

Nemanja Trifunovic