Name Your Variables

As you sit and madly pound out code, variable names are probably not at the top of your list of things to do better. I tend to use x for my loops, c or ch for characters, and other variables, including a, b, and c. This is an acceptable approach, but for larger programs such variable names not doing you any favors.

Variable names can be descriptive. They could tell you something about the value they represent, which adds readability to your code. For example:

s = d/t;

Obviously the above statement is some sort of equation, which you can understand if you’ve been studying C for longer than a day. The following example works better, thanks to more descriptive variable names:

speed = distance/time;

I’m also a fan of something called medial capitalization for my variable names. This is technique is also known as camel case, simply for the “humps” it puts in the names:

int retryAttempts, valueOverTime, initialEggCondition;

Because spaces aren’t allowed in variable names, many programmers opt to use an underscore to separate “words” in a variable name:

int retry_attempts, value_over_time, initial_egg_condition;

I admit that this technique does make the variable names easier to read, but it’s not as easy to type.

You can’t use a hyphen (the - character) in a C variable name as it’s interpreted as the subtraction operator.

Microsoft uses Hungarian Notation for their variable names. The idea is to identify the type of variable by looking at its name. For example, the variable name szAddress is a null-terminated string, lHeight would be a long int variable, and so on.

You can read more about Hungarian Notation on Wikipedia, which offers some examples.

The C language lacks any specific rules on variable names, although one limitation is common: Internal variables are named with a double underscore prefix. If you’ve ever spelunked in the header files, then you’ve probably seen variables like __secret. The double underscore identifies these internal variables, flagging them as special.

It’s recommended that you don’t begin a variable name in your C code with an underscore or double underscore prefix and to avoid double underscores within a variable name. Aside from that, start the variable name with a letter, then use upper case, lower case, underscores, and even numbers if you like.

My advice is to keep the variable names descriptive. That’s always a plus.