Convention in C/C++

This is a discussion on Convention in C/C++ within the C++ Programming forums, part of the General Programming Boards category; Hi, I know there's some conventions on variable naming and coding. I know only a few of them like: 1. ...

  1. #1
    In the Land of Diddly-Doo g4j31a5's Avatar
    Join Date
    Jul 2006
    Posts
    476

    Convention in C/C++

    Hi, I know there's some conventions on variable naming and coding. I know only a few of them like:
    1. "m_...." for naming a member variable of a class
    2. "c_..." for naming a constant variable
    3. All caps for defining macros

    Does anybody know any other convention?

    Also, what about assert vs try-catch-throw? Any insight?

    Thanks.

  2. #2
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    My Website
    010000110010101100101011
    Add Color To Your Code!

  3. #3
    Frequently Quite Prolix dwks's Avatar
    Join Date
    Apr 2005
    Location
    Canada
    Posts
    8,046
    Well, depending on what convention you follow, there are many different rules.

    One, called Camel Capitalization (because that's what it looks like), has you capitalize the first letter of every word: thisIsAVariable.

    Hungarian notation is . . . well . . . complicated. You can tell from the name alone what type the variable is. For example, pPointer is a pointer. You've probably seem funny names like pzrVar. I don't use it so I can't give you any other examples.

    I usually use this_is_a_variable.
    dwk

    Seek and ye shall find. quaere et invenies.

    "Simplicity does not precede complexity, but follows it." -- Alan Perlis
    "Testing can only prove the presence of bugs, not their absence." -- Edsger Dijkstra
    "The only real mistake is the one from which we learn nothing." -- John Powell


    Other boards: DaniWeb, TPS
    Unofficial Wiki FAQ: cpwiki.sf.net

    My website: http://dwks.theprogrammingsite.com/
    Projects: codeform, xuni, atlantis, nort, etc.

  4. #4
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    I prefer:

    variableName
    ClassName
    MethodName

    as my style of coding. I never liked hungarian notation. I find it redundant in a strongly-typed language.


    As to asserts vs. exceptions -- apples and oranges, though if you had to pick just one to use, pick exceptions.

    Asserts are useful in debugging code; they should be used to check for conditions which a properly coded program should never cause (e.g. a NULL pointer being passed where it could not be). Asserts are checking to make sure your code is correct. Those asserts no longer exist in your release code, because presumably you fixed your code bugs. An assert also always terminates your program -- there's no chance for error recovery, or anything like that.

    Exceptions are far more broad -- for example, if you have a program which downloads information and the URL is temporarily unavailable, that would be a decent time for an exception. Then it's up to the caller of the method to decide how to handle it -- let it crash the program (bad) or gracefully recover (good).

    * If the check is unnecessary if the program is assumed to have no bugs, use ASSERT (although exceptions work too). Cases like this would be checking for NULL pointers passed into your function (assuming you didn't specify that as a valid choice)

    * If the check is still necessary even if the program is bug-free, use an exception (ASSERT won't work, unless you plan to live your life in debug mode). Cases like this would be checking if a file was successfully opened (another process could have that file locked, that's not a program bug), or validating user input.
    Last edited by Cat; 08-28-2006 at 09:30 PM.
    You ever try a pink golf ball, Wally? Why, the wind shear on a pink ball alone can take the head clean off a 90 pound midget at 300 yards.

  5. #5
    Ethernal Noob
    Join Date
    Nov 2001
    Posts
    1,901
    I'm used to Camel Capetalization from Java. But the book I'm teaching does use the underscore word separation. That usually confuses me because most functions use underscore separation, so I leave variables CCd and functions with underscores.

  6. #6
    Registered User
    Join Date
    Dec 2005
    Posts
    25
    I use different conventions for C and C++. In C, I use the variable_name and function_name() convention (since most of my C coding tends to be for GTK+ anyway). In C++ I prefer the following:

    * VariableName
    * CClassName
    * Verbs in Class Method Names (e.g. GetThis() or DisplayThis())

  7. #7
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,436
    There's no convention oter than the one you establish yourself. Of course some things should never be done, like using long names or naming a variable apples when it should be named oranges. The key point is consistency. Use the same style throughout the application. And choose your own. As you keep programming, no matter the language, you will soon find yourself adopting one.

    . My classes start with C followed by word capitalized names. CPlayer, CHouse, CInventory.
    . My private data members all end with an underscore and no capitalization. name_, status_, level_.
    . Private member functions follow the same naming convention for data members. As in fact, anything that is private does.
    . I prefer to separate words with underscores. blast_radius.
    . operator overloading usually has pretty simple semantics. If another user defined object, it's called simply obj. If a std::string or C-style string, it's called str. All arithmetic types are called val. On non member operator overloading I always prefix with l and r (standing for left and right operand)

    I usually have a few personal rules I try to stick to. Some probably good, some probably bad, some probably outright wrong:

    . I postfix all pointers (and the same with pointers defined inside a class) with _ptr. player_ptr, account_ptr.
    . If I'm using safe pointers, I postfix owner pointers with _ptr as normal (even if I'm using shared pointers), but weak pointers with _wptr.
    . All my iterators are named iter. If the name already exists in scope due to another iterator presence, I append x, y, z, m or n respectively (this is from my school days in naming variables for math calculations).
    . Following the same convention as above reverse iterators are named riter, and insert operators are named iiter.
    . My regular variables are usually all small_caps with words separated by underscores.
    . function parameters, are a special case. I almost always try to make them follow the same rules as for operator overloading above. If the meaning of the variable is non-important, it will invariably be called str, obj, val, or some other generic name. I will otherwise use a regular variable name, if I think the meaning of the variable is important to understand the code inside the function or it's important in order to understand the context of the function.

    I can't remember any more examples... There are more. The important bit is for you to be consistent about it. This is not a part of the programming language. It's a part of you. It's part of your coding style. Everyone reading your code is not asked to like or not your coding style. They are required instead to understand it. And you are required to make it easy for them by being consistent.
    Last edited by Mario F.; 08-29-2006 at 03:28 AM.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  8. #8
    Registered User Osaou's Avatar
    Join Date
    Nov 2004
    Location
    Stockholm, Sweden
    Posts
    69
    Mario summed it up pretty nicely, albeit with a rather ugly convention... But hey, all conventions that aren't exactly like mine are ugly, right?
    (Edit: Sorry Mario, don't take it personally)

    Speaking of which, here it is:

    [c][a][r][p][e][type]_[name]

    The prefixed characters enclosed in brackets (lower-case) denote special characteristics regarding the variable (or such being returned if it's a function/method name). Here are their explanations:
    • c = constant
    • a = function/method argument; especially handy for regularly used names like x,y,z etc...
    • r = reference
    • p = pointer
    • e = enumerator


    type is either:
    1. an identifier in lower-case letters referencing one of the following built-in types C++ support:
      • s = signed, must immediately be followed by further type identification
      • u = unsigned, same as above
      • b = single byte or boolean value (bytes are obviously pre-fixed by either s or u, explained above)
      • w = word, i.e. 2 bytes
      • dw = double word, i.e. 4 bytes; 32bit integer
      • qw = quadruple word, i.e. 8 bytes; 64bit integer
      • f = real value float
      • d = real value double
      • l = long double
      • v = void
    2. or, if it's a custom type (class, struct, enumerator), the first letter of each word forming the type's name are stringed together in upper-case.


    The semantics for name differs between storage, custom types and functions/methods like so:
    • storage = all lower-case, words separated by underscore, e.g: int sdw_my_integer;
    • functions/methods = first letter in each word upper-case, words not separated, e.g: bool b_IsOpen(void);
    • custom types = same as for functions/methods except there's obviously no type prefix



    Some examples:
    Code:
    struct Vertex{
    	float f_x;
    	float f_y;
    	float f_z;
    	float f_w;
    };
    
    
    template <typename T>
    class List{
    	...
    };
    
    
    class Vehicle{
    private:
    
    	List<Weapon> LtG_guns;	// list templated with the type "Weapon"
    	Vertex *pV_pos;
    	int sdw_guns;		// notice I don't have to name it "amount" because that's implicated by the fact that it's an integer
    	char *psb_name;
    	bool b_airborne;
    
    public:
    
    	enum Flags{
    		eF_rgb,
    		eF_textured
    	}
    
    
    	Vertex &rV_Position(void);
    
    	int sdw_Guns(void);
    	void v_Guns(int asdw_guns){
    		// simple to see which one is the argument and vice versa, even though "they have the same name"
    		sdw_guns = asdw_guns;
    	}
    
    	char *psb_Name(void);
    
    	bool b_IsAirborne(void);
    
    	void v_Draw(void);
    };
    
    
    
    Vehicle V_car;
    
    int sdw_car_guns = V_car.sdw_Guns();		// sdw_x = sdw_y;	simple and sweet
    Last edited by Osaou; 08-29-2006 at 10:01 AM.

  9. #9
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    I normally just a selective kind of Hungarian - Just p for Pointers and that's it I don't see the need to prefex something with a sz for string when you can describe the variable by calling naming it ...

    string MyStringThingNotAnIntNotABoolJustAString;

    etc

  10. #10
    and the hat of wrongness Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    32,490
    Why I don't like hungarian notation - yes, this is my biased opinion.

    1. It results in an unreadable mess - how do you pronounce pszMyString. Some of the longer ones take way too much time trying to work your way through them.
    Personally, I prefer my code to be readable, this kind of cryptic crap just gets in the way of me reading code.

    2. There are many bastardised variations - some code the type, some code the scope, some may add qualifers, others just mix and match. Unless you 'get' the particular flavour, the result is pretty meaningless.
    Mostly, it seems to be the author's over-reaction to whatever previous bad experience they had, so they go overboard with the naming to try and address that prior issue.

    3. There is no means to check the name, because there are so many variants.
    Given pszMyString, what would your reaction be to actually finding
    double pszMyString;
    The compiler certainly isn't going to complain, it's just another symbol and so long as it makes sense it couldn't give a monkeys about the name.

    4. Primitive types like int and double are first class types and everything else is lower class.
    I mean, given struct coord { int x, int y }; one could argue that you should declare
    coord structContaining_IntX_IntY_MyVariable;
    rather than saying 'st' is the prefix for all structures eg.
    coord stMyVariable;
    Obviously that gets completely stupid for large and nested structures.

    The st is of course meaningless, because all those .member and ->member references really give the game away.

    5. Portability is lost.
    Say during some maintenance phase you decide you want an unsigned long for something rather than an unsigned short. Instead of just changing the type, you have to hunt through all the code and change all the 'us' variables into 'ul' variables. How often is this done - not as often as you might imagine. Unless you have a really good editor, global replace of such short sequences is bound to come unglued, so few attempt it.

    6. typedef unsigned long colour_t;
    Now is this a 'ul' variable, or do you name it something else?
    That is, do you smash your way through the abstraction to the core underlying type or do you name it something else?

    7. If you have a class which is completely abstracted, that is you can only access it via it's published methods, then you simply have no information about its insides to even begin to give it some cryptic prefix.

    8. Today, features such as intellisense are perfectly capable of giving you the actual information rather than you having to manually extract it from a possibly incorrect name.

    You might be able to make it consistent in a short-lived personal project, but in a commercial environment, it just breaks down over time if there is no strong code review or enforced checking tools.
    If you dance barefoot on the broken glass of undefined behaviour, you've got to expect the occasional cut.
    If at first you don't succeed, try writing your phone number on the exam paper.
    I support http://www.ukip.org/ as the first necessary step to a free Europe.

  11. #11
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,436
    Quote Originally Posted by Osaou
    (Edit: Sorry Mario, don't take it personally)
    No offense taken. How could it be otherwise
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  12. #12
    Anti-Poster
    Join Date
    Feb 2002
    Posts
    1,399
    Those are all pretty good reasons why I don't use type-Hungarian. I do use more of a function-Hungarian. Any idiot can look at code and know that a variable is an int, but what does the variable do? It also helps you catch errors. I do XFromY functions all the time; it just makes it easier to grok the code.
    If I did your homework for you, then you might pass your class without learning how to write a program like this. Then you might graduate and get your degree without learning how to write a program like this. You might become a professional programmer without knowing how to write a program like this. Someday you might work on a project with me without knowing how to write a program like this. Then I would have to do you serious bodily harm. - Jack Klein

  13. #13
    (?<!re)tired Mario F.'s Avatar
    Join Date
    May 2006
    Location
    Portugal
    Posts
    7,436
    There's a variant of Hungarian notation I once saw being used by a former workmate which was slightly interesting. Hungarian notation is strongly typed (if such thing can be said of a naming convention). However this fella used the same principle of variable prefixing but with a focus on the variable context, not on its type.

    I was once a huge supporter of hungarian notation. I couldn't agree with the criticism until I started to abstract myself of the whole debate and realized that I was in fact constantly finding myself trapped by my naming conventions for the very same reasons Salem pointed out (although I strongly disagree with point 1).

    This fella, he developed his own convention based on the context of the variable. It had some merits. Let's see if I remember some of it:

    . variables used as flags were prefixed with f. fValue, fTest
    . variables used for iteration were prefixed with i. i, ix, iy,...
    . variables with regular storage use were prefixed according to their contents. strName, valStrenght, ...
    . I can't seem to remember how he did arrays.

    This was many years ago when I was in a company developing in LightShip and Command Center ++ (known back then as CC++... not to confuse with the C++ subset of the same name). So I can't remember all details. I did find it easy to follow his code after I got used to it though.
    The programmer’s wife tells him: “Run to the store and pick up a loaf of bread. If they have eggs, get a dozen.”
    The programmer comes home with 12 loaves of bread.


    Originally Posted by brewbuck:
    Reimplementing a large system in another language to get a 25% performance boost is nonsense. It would be cheaper to just get a computer which is 25% faster.

  14. #14
    Registered User mrafcho001's Avatar
    Join Date
    Jan 2005
    Posts
    483
    I never said Hungarian notation was good, nor that i use it. I dont really have a convention.. but my code is something like this:

    varName
    funcName
    ClassName

    with pre-fixes and post-fixes in some cases
    My Website
    010000110010101100101011
    Add Color To Your Code!

  15. #15
    The superhaterodyne twomers's Avatar
    Join Date
    Dec 2005
    Location
    Ireland
    Posts
    2,262
    Quote Originally Posted by mrafcho001
    I never said Hungarian notation was good, nor that i use it. I dont really have a convention.. but my code is something like this:

    varName
    funcName
    ClassName

    with pre-fixes and post-fixes in some cases
    I don't know. I tink you sent me some source for your TTT game, and I seem to remember there being some Hungarian in it ... I think. I have to put the Color Coder back on my sig

Page 1 of 2 12 LastLast
Popular pages Recent additions subscribe to a feed

Similar Threads

  1. calling convention stdcalll and cdecl call
    By George2 in forum Windows Programming
    Replies: 1
    Last Post: 07-17-2008, 03:26 AM
  2. What do you think of this C++ naming convention?
    By cnsr in forum C++ Programming
    Replies: 10
    Last Post: 01-07-2004, 07:51 PM
  3. Replies: 2
    Last Post: 01-04-2003, 12:16 AM
  4. VB Calling Convention?!
    By minime6696 in forum Windows Programming
    Replies: 6
    Last Post: 03-27-2002, 03:39 PM
  5. Maya Convention
    By DavidP in forum A Brief History of Cprogramming.com
    Replies: 3
    Last Post: 03-01-2002, 10:10 PM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21