Add to Technorati Favorites

All About Identifiers in C++

In our everyday, we give names to different things so they can be referred easily. Similarly, in C+, we use identifiers to name user created entities which may be:
  • Variable
  • Function
  • Type e.g. a class

Every thing has some restrictions and exceptions along with many permissible things. So, does C++ by putting some restrictions on how we can name these entities. Let us see these rules in details:

1. An identifier can be combination of letters, numbers, and underscores with following restrictions:

a) It should start with a letter or underscore. E.g. height, my_height,_myHeight are allowed but not 1isGod
b) If it starts with a underscore then the first letter should not be capital because such names are reserved for implementation. E.g. _Height not allowed

2. It should be unique in a program taking care that C++ is case sensitive. E.g. age and Age are different variables

3. A keyword cannot be used as an identifier.

4. There is no restriction on length of the identifier. E.g. h and h_represents_my height are both valid.

Besides restrictions, there are certain guidelines which you should follow:

a. Use meaningful descriptive names. E.g. int Age is better than int a.
- If description makes identifier name too long then put a comment before identifier and make identifier shorter
b. Be consistent in your naming convention.
- Use small letters for single word identifier name.
- For multiword identifiers, either use underscore separated or interCapped notation. E.g. get_my_height() or getMyHeight()
c. Use Hungarian notation. E.g. double dFlowRate, int nValue, bool bCheck.
d. Don't use similar names in a program like Speed, speed, and Speedy
e. Don't use capitalized version of a keyword like Return

In tommarrow's post, we will see different data types available in C++ and rules for their declaration, initialization, and assignment.

No comments: