• Advertisement

Archived

This topic is now archived and is closed to further replies.

C/C++ programming style

This topic is 6336 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts

i always wondered about function names. it seems its divided amongst some different style BigYes() bigYes() bigyes() reasoning behind each of them?

Share this post


Link to post
Share on other sites
Advertisement
You missed another popular one: big_yes()

I usually use BigYes and start all my variables with a lower case letter followed by uppercase for each word. It doesn''t really matter which you choose, as long as you''re consistent with it.

Share this post


Link to post
Share on other sites
Everything but big_yes is good because you need one less character (not saying big_yes is bad! Of course!). Another thing with using BigYes is to make it look different than the C/C++ RT functions and such and thus being able to seperate your functions from runtime C/C++ functions quickly (and espec. for thrid party readers). Some see it the other way around, however.

I use the BigYes style for functions, class- and struct names (I also have a prefix on them quite often eg. gzVector3f if it''s in a library etc.) and big_yes for variables. It''s just a matter of personal likings.

"Paranoia is the belief in a hidden order behind the visible." - Anonymous

Share this post


Link to post
Share on other sites
Big_Yes() is my preference.

although, big_yes() is kind of cool...no capital letters...a little easier





"NPC's are people too!" --dwarfsoft

"Nazrix is cool." --Nazrix first, then Darkmage

Share this post


Link to post
Share on other sites
I think "big_yes" names don''t just look stupid, but they are impractical, so there. I however also use hungarian notation all over my program and think its a good idea too, it lets you know what a variable is without having to jump to its definition. And according to the function naming, MixedCase by capitalizing the first letter in each word is truly the way to go. I also have a habit of placing acronyms of what module they belong to as well. such as:
DDInit()
DDShutdown()
DSPlay()
FEPutText()

I also believe in underscores by placing them in front of names. For instance, when using objects and functions, I have a hard time declaring variables that fill in member structures without using the actual variable name, so to solve this I place an underscore in front like _NumOfVertices or _NumOfPolygons.

I also never really found too much reasoning in creating variable like m_MyMember or g_MyGlobal. I suppose someday I may actually do that, it seems like a good method of letting other programmers know that you are dealing with member names and global variables.

- Tom

Share this post


Link to post
Share on other sites
olp-fan,
Yeah, if you''re planning on having other programmers looking at your code & working w/ it then those styles are good I suppose...even if it''s an M$ idea

But working on my own, I know what types things are...I''m probably developing bad habbits but oh well




"NPC's are people too!" --dwarfsoft

"Nazrix is cool." --Nazrix first, then Darkmage

Share this post


Link to post
Share on other sites
I use whatever seems reasonable at for the application.
For instance, I might do
putpixel()
fRand().
Generally I use either all upper or lowercase





I came, I saw, I got programmers block.
~V''lion

Share this post


Link to post
Share on other sites
quote:

I place an underscore in front like _NumOfVertices or _NumOfPolygons.

I also never really found too much reasoning in creating variable like m_MyMember or g_MyGlobal



Here''s a reason for you Any name starting with _ followed by another _ or A to Z (so that''s _[A-Z_]) is reserved for the implementation at any scope (e.g. a macro). So you could included a standard header and it''s perfectly legal for it to do "#define _NumOfVertices 10" which will break your code. Personally I use m_ for members, but some people like a trailing underscore.

Share this post


Link to post
Share on other sites
quote:

i always wondered about function names. it seems its divided amongst some different style



If you''re working on your own, you can name functions and variables as you want to and generally do as you wish... Most home programmers do it this way as everybody like to think that their way is best...

...But if you ever want to work for a company which demands high standards and multi-developer projects you''ll be forced to program in a more standardised way...

This usually means the correct use of prefixing, hungarian notation, and standardised function naming:-

In C, function names really need to be prefixed, due to lack of namespaces... Generally people use the ''bigYes()'' format like in OpenGL:- glEnable, glFlush, etc.

When working with namespaced functions in like in C++ however, prefixing function names is generally unnecessary. Logic would dictate that you remove the lower case prefix and end up with mixed case names in ''BigYes()'' style.

I don''t know about anywhere else, but where I work, names which are all lower case represent common/pre-defined library functions like ''strncpy()'' that you''d normally get with the compiler...

As for underscores I don''t know... I only ever use them within constants and enums, I find that underscores in function names make it difficult to tell them apart from my constants

Jans.

Oh, and olp-fan , you say you use hungarian notation throughout and then go and name two variables with underscores and no prefixing, what''s wrong with ''iNumVertices'' or ''iVertexCount''???

-----------------
Janucybermetaltvgothmogbunny

Share this post


Link to post
Share on other sites
Hey guys, instead of using things like DDInit(), you should try DD::Init(). Namespaces are a wonderful feature. Say you have one source file for High Scores, one for Main Menu, one for Play Processing, etc. It''s much better to go with namespaces like HS, MM, PP, etc than to use certain styles for each source file. Just my 2 cents.

-Domenic-
Geek^n

Share this post


Link to post
Share on other sites
BigYes, bigYes and big_yes all serve the same purpose, to make visible boundaries between different words in the identifier (since you can''t use spaces). It''s a readability issue. My personal preference is for all lowercase names with underscores where necessary. Any one of them should be just fine.

Using capital letters (or some other convention) to distinguish types (classes) and variables is probably a good idea, but unfortunately not one I''ve been able to adopt.

I fail to see the benefit of hungarian notation, especially in a strongly typed language like C++. The m_MyMember and g_MyGlobal idea appear to be less extreme but similar to hungarian notation, and not very useful.

Using prefixes for different groups of names was a good idea in C, but in C++ you really should use namespaces instead. They are far superior.

Oh, and I certainly wouldn''t want to read (much less maintain) any of olp_fan''s code...

Share this post


Link to post
Share on other sites
quote:
Original post by spock
I fail to see the benefit of hungarian notation, especially in a strongly typed language like C++.



I wouldn''t classify C++ as a strongly typed language at all, and strong typing doesn''t alleviate the _need_ for prefixing, I still prefix when coding in Java...

quote:
Original post by spock
The m_MyMember and g_MyGlobal idea appear to be less extreme but similar to hungarian notation, and not very useful.



It helps prevent name collisions, imagine a class with a member variable ''m_iCount'' which you want to initialise from the constructor:-



CClass::CClass(int iCount)
{
m_iCount = iCount;
}


It''s easy to see, easy to read, and you don''t need to think of some novel name for your parameter (like you would if you''d called the member variable ''iCount'')


Jans.


-----------------
Janucybermetaltvgothmogbunny

Share this post


Link to post
Share on other sites
Ok, I''ll start this off by saying there is NOT a right style, nor even a difinitive argument for better and worse styles, BUT there ARE aspects of various styles that can be taken into account when deciding what style you want to use.

These ideas are mostly my own, learned through the last 3 years making style decisions for a small team of programmers (2-4), but they were originally influenced by the book "Code Complete" which I recommend every programmer to have as a reference, and to read at least once. (The only book I think is more important is "Design Patterns").

First I will get out of the way, the style I currently use. Then I will mention one or two opinions I have about other styles. Once again, I DO NOT think my style is the best style in the world, and it will continue to evolve as I learn new things or change my attitude about style goals.

My Style:

Function and Class Names: Mixed Case
TraverseTree()
ScreenManager
HPTimer

Variables: Leading Lower Case Then Mixed Case
primarySurface
changedFlag

Macros and Global Constants: All Caps
MAX_LINE_LENGTH
NULL
VERSION_NUMBER

Ok, now its time for some of my reasons. There are only TWO principals I followed when making my style decisions, and I believe if you follow these two goals, your style will be good, no matter if it differs from mine in every detail.

Principal One: Readability

What I mean by this is the same as in use of whitespace. On the screen and on the page, your eye should be able to flow over the code, extracting important information, but not getting bogged down by unwanted detail. The structure of the program should be made more, not less, clear by the style you use. As a corralary to this is the concept of Conservation - overuse of any form of symbol (like hungarian notation) or emphisis mark (like ALL CAPS) takes the meaning away from the symbol.

Principal Two: Encapsulation
This is my primary argument against hungarian notation (which is the ONLY popular style I have a problem with). My contintion (for which I have run no experiments to prove) is that it is NOT a good idea to display type information in the code, as this is COMPLETELY CONTRARY TO OBJECT ORIENTED PROGRAMMING. The idea of object oriented programming is encapsulation and data hiding, the fundamental idea is ABSTRACTION (omiting of certain detials in order to see the wholistic structure better). The whole point of polymorphism is so that different derived classes may be treated the same, the whole point of classes is so that implementation details may be ignored, and FOR ME, the whole point of naming conventions is so that THE INTENDED USE of a variable / function / or class can be made clear. The header file and code itself will tell you what class an object is and the details of its use (in modern editors this pops up as TOOL TIPS, and there are also dozens of automated tools to generate this kind of documentation) so as a programmer, the only way you can add value is to use names that provide ADDITIONAL / DIFFERENT information than what the language syntax implies.

I will give one overly simplified example to make my point:

Version One:

bool TestFunction(const Shape &s, cosnt Point &p)
{
bool returnVal = false;
if(BLAH BLAH)
returnVal = true;
return returnVal;
}

Version Two:

bool IsPointInRegion(const Shape ®ion, const Point &pointToTest)
{
bool isInside = false;
if(BLAH BLAH)
isInside = true;
return isInside;
}

Well ... that example wasn''t the greatest, but hopefully you can see what I''m talking about. A variable named ''tempString'' is only better than a variable named ''temp'' if there are a bunch of other variables named ''tempInt'' ''tempFloat'' etc. usually you would be much better off to name the varaible based on its USE not it''s type, such as ''errorMessage''

That brings me to the end of my diatribe, at some latter date I''ll try to clean this up into an article and post it (but of course I provide much more detail and explore other styles than my own).

Until then.

Share this post


Link to post
Share on other sites
quote:

..."Code Complete" which I recommend every programmer to have as a reference, and to read at least once.



I really didn''t like this book, I only got about half way through before I got sick. It does have some good suggestions, but I wouldn''t put it in same league as Design Patterns.

quote:

(The only book I think is more important is "Design Patterns").



I''d say The C++ Programming Language and The C++ Standard Library are both much more useful than Code Complete. Writing Solid Code is good however (and it''s also the reason I got Code Complete), and everyone should read it.

Share this post


Link to post
Share on other sites
(This is all opinion, too, so it may be worded a little strongly - I don''t mean anything by it! )


quote:
Original post by Jansic

quote:
--------------------------------------------------------------------------------
Original post by spock

The m_MyMember and g_MyGlobal idea appear to be less extreme but similar to hungarian notation, and not very useful.
--------------------------------------------------------------------------------

It helps prevent name collisions, imagine a class with a member variable ''m_iCount'' which you want to initialise from the constructor:-



Not really - the compiler can tell constext and scope:


class test
{
public:
test(int data);

private:
int data;
};

test::test(int data)
: data(data) {}



No ambiguity there, it compiles fine, and does what it''s intended to do. You can also do this, in case you have to work with heap memory (which should not be constructed in the same way):


test::test(int data)
{
this->data = data; // tell it which one!
}



If the feature exists in the language, use it. Don''t invent rules that muddle up the code.

Oh, and the proper way of telling a C++ programmer that something is in global scope is to:


int x; // a global variable!

int main(int, char*)
{
::x = 5; // it''s a global!!
}



You have to use that method to refer to things of other scope (like namespaces!), so you should use it for globals, too, in order to be consistent.


BTW, I use the all-lowercase and underscore stuff, as it helps me to write meaningful, one-word variables without a lot of fuss. Besides, code is formed from "statements" (<-- anyone see a relation to English!), and we don''t talk like anything else. Because of the way most languages are designed, we have to use the underscore in place of a space, as multi-word identifiers aren''t allowed.

gotta go now!

Happy Coding!



- null_pointer
Sabre Multimedia

Share this post


Link to post
Share on other sites
Hmm, maybe Microsoft should read there own books.

-----------------------------

A wise man once said "A person with half a clue is more dangerous than a person with or without one."

Share this post


Link to post
Share on other sites
Well, not everything is correct in MSVC...for example, the compiler seems to mess up these declarations sometimes (seemingly randomly?):


class size {};

class map
{
size size;
};



That code should compile fine, because the compiler can certainly tell between the data member and the type, as the data member and the type are in different scopes:


class ::size; // a global
::size ::map::size; // data member is inside the map scope!



Sometimes in my code VC just chokes on this stuff - I''m not sure why but when it does they happen to be in completely different scopes (I''m sure of it!).

(This will not work in any compiler: )


class map
{
class size {};
size size;
};



You can''t have two identifiers in the same scope meaning different things:


class ::map::size;
::map::size ::map::size; // illegal!



There is no need for notation if you know the language, and don''t have to maintain tons of poorly written C++ code (1000-line functions, code that declares all objects at the beginning of the function, etc.).



- null_pointer
Sabre Multimedia

Share this post


Link to post
Share on other sites
quote:
Original post by Jansic
I wouldn't classify C++ as a strongly typed language at all, and strong typing doesn't alleviate the _need_ for prefixing, I still prefix when coding in Java...



Perhaps strong typing was somewhat beside the point. What I was thinking of was something along the lines of what Xai wrote about abstraction:

quote:
Original post by Xai
the only way you can add value is to use names that provide ADDITIONAL / DIFFERENT information than what the language syntax implies.



Typing is important information provided by the language syntax, but not necessarily the only information. Anyway, I do classify both C++ and Java as strongly typed languages. What makes you think otherwise?

Edited by - spock on September 3, 2000 2:41:25 PM

Share this post


Link to post
Share on other sites
quote:
Original post by null_pointer

(Besides, code is formed from "statements" (<-- anyone see a relation to English!), and we don''t talk like anything else.


Well, if we''re gonna get pedantic and compare with English, lines of code are more like directives than statements

For the record, I use the same conventions as Xai (capitalised functions, mixed case variables, uppercase with underscores constants) and don''t agree with Hungarian notation or global/member prefixes mainly because I don''t think they are needed in well encapsulated code, and therefore just adds clutter and hampers readability. (Give me ''name'' over ''m_lpcstrName'' any day.)

Share this post


Link to post
Share on other sites
Ok, Here are my 2 cents worth...

( someone said this: although, big_yes() is kind of cool...)

Well, this is the proper way according to the Ansi C standards of my college years but now, It''s evolved a bit. My method of choice is:

int generalArbitraryValue;

I''ve always used the method mentionned above. The first word is in small and the rest of the words start with a capital. This is the way that I''m most comfortable with.

This is my 2 cents...



Cyberdrek
Headhunter Soft
DLC Multimedia

Share this post


Link to post
Share on other sites
If it is a function specially for that project, I will use big_yes() style. If is part of a library which I made, i will put the name of the library in lower case letters, followed by the BigYes() style. Structure names are ALL CAPS, and so are macros. Variable names are in the big_yes style again, unless they are external, in which case they are Big_Yes.

------------------------------
#pragma twice


sharewaregames.20m.com

Share this post


Link to post
Share on other sites
I was reading this and came up with a new simple way of naming items.
functions: CWindowText
variables: b_text_active

Very simple. Hungarian can still apply.
Now in my code if I see this CWindowText, not only do I know it''s a class vs. a variable, I also note the missing ().
This means I could possible be using the wrong constructor.

Perhaps this already exists, but I personally have never seen it.

Share this post


Link to post
Share on other sites
I have a theory, that the C enthusiest''s use more lower case names, than the C++''ers(or poeple who ONLY use C++), use more Caps, just my theory,
later,(Im going cruzin in a 2001 Camero now, C U later)

Share this post


Link to post
Share on other sites

  • Advertisement