Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations Chris Miller on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

How should i name my variables?

Programming

How should i name my variables?

by  Skute  Posted    (Edited  )
Hungarian Notation

When naming variables there are many different methods you can use. By far the best and most wide-spread method is called "Hungarian Notation". This involves prefixing names of variables with a short character(s) representing the datatype of the variable. Coders all over the world use this type of notation, so if possible, it is best to use it because it will be alot easier for anyone else picking your code to understand.

Here are some examples:


Numbers
// This variable is an integer, and is involved in some counting procedure
int iCount = 0;
// A floating point number for measuring height
float fHeight = 0.0f;

So when you come across these 2 variables in your code you should be able to quickly and easily identify what type they are and what purpose they have.

With numbers types it is also common for people to use the "n" prefix, which simply means number. So the previous 2 examples would become:

int nCount = 0;
float nHeight = 0.0f;

But i dont like that way as much because you cant quickly tell which type the variable is.

The usage of nHeight makes it easy to change the type of a variable later on in your code, imagine you want to change from a int to a float. If your variable is iHeight, everywhere in your code that will need to be changed to fHeight. Using a standard nHeight (number) will mean that you only need to change its type definition.


Strings

char szName[256] = "Skute";
char szName2[] = "Skute2";

The "sz" prefixing the name of the variable means "string terminated with a zero (NULL)". So for example, the variable szName2 can be read as:

szName2[0] = 'S'
szName2[1] = 'k'
szName2[2] = 'u'
szName2[3] = 't'
szName2[4] = 'e'
szName2[5] = '\0' (NULL)

Here are some other ways of writing string definitions:

char* pszCountry = "England";

The "psz" here means "pointer to a string terminated with zero (NULL)".

string strDog = "Spike";
CString strCat = "Tom";

Here the "str" means string type or string class.


Member and global variables

When variables belong to a class they can be named slightly different so they are easier to identify then local variables. For example:

int m_iPort = 3306;

The "m_i" prefix means "class member of type integer"

Or similarly:

char* g_pszConnection = "Server=localhost";

Can be read as "global pointer to a string terminating with zero (NULL)".

Register to rate this FAQ  : BAD 1 2 3 4 5 6 7 8 9 10 GOOD
Please Note: 1 is Bad, 10 is Good :-)

Part and Inventory Search

Back
Top