What is a good naming convention for vars, methods, etc in C++?

C++Naming Conventions

C++ Problem Overview


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.

C++ Solutions


Solution 1 - C++

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.)

Solution 2 - C++

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.

Solution 3 - C++

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 ;-)

Solution 4 - C++

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.

Solution 5 - C++

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

Solution 6 - C++

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 ;).

Solution 7 - C++

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_ */

Solution 8 - C++

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.

Solution 9 - C++

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.

Solution 10 - C++

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionnacho4dView Question on Stackoverflow
Solution 1 - C++GManNickGView Answer on Stackoverflow
Solution 2 - C++Matthieu M.View Answer on Stackoverflow
Solution 3 - C++PhilippView Answer on Stackoverflow
Solution 4 - C++missingfaktorView Answer on Stackoverflow
Solution 5 - C++Nemanja TrifunovicView Answer on Stackoverflow
Solution 6 - C++Kornel KisielewiczView Answer on Stackoverflow
Solution 7 - C++justinView Answer on Stackoverflow
Solution 8 - C++Alexander RaffertyView Answer on Stackoverflow
Solution 9 - C++GozView Answer on Stackoverflow
Solution 10 - C++antoniuslinView Answer on Stackoverflow