Search

1.7 — Keywords and naming identifiers

Keywords

C++ reserves a set of 84 words (as of C++17) for its own use. These words are called keywords (or reserved words), and each of these keywords has a special meaning within the C++ language.

Here is a list of all the C++ keywords (through C++17):

  • alignas (C++11)
  • alignof (C++11)
  • and
  • and_eq
  • asm
  • auto
  • bitand
  • bitor
  • bool
  • break
  • case
  • catch
  • char
  • char16_t (C++11)
  • char32_t (C++11)
  • class
  • compl
  • const
  • constexpr (C++11)
  • const_cast
  • continue
  • decltype (C++11)
  • default
  • delete
  • do
  • double
  • dynamic_cast
  • else
  • enum
  • explicit
  • export
  • extern
  • false
  • float
  • for
  • friend
  • goto
  • if
  • inline
  • int
  • long
  • mutable
  • namespace
  • new
  • noexcept (C++11)
  • not
  • not_eq
  • nullptr (C++11)
  • operator
  • or
  • or_eq
  • private
  • protected
  • public
  • register
  • reinterpret_cast
  • return
  • short
  • signed
  • sizeof
  • static
  • static_assert (C++11)
  • static_cast
  • struct
  • switch
  • template
  • this
  • thread_local (C++11)
  • throw
  • true
  • try
  • typedef
  • typeid
  • typename
  • union
  • unsigned
  • using
  • virtual
  • void
  • volatile
  • wchar_t
  • while
  • xor
  • xor_eq

The keywords marked (C++11) were added in C++11. If your compiler is not C++11 compliant (or does have C++11 functionality turned on by default), these keywords may not be functional.

C++11 also adds two special identifiers: override and final. These have a specific meaning when used in certain contexts but are not reserved.

You have already run across some of these keywords, including int and return. Along with a set of operators, these keywords and special identifiers define the entire language of C++ (preprocessor commands excluded). Because keywords and special identifiers have special meaning, your IDEs will likely change the text color of these words (often to blue) to make them stand out from other identifiers.

By the time you are done with this tutorial series, you will understand what almost all of these words do!

Identifier naming rules

As a reminder, the name of a variable (or function, type, or other kind of item) is called an identifier. C++ gives you a lot of flexibility to name identifiers as you wish. However, there are a few rules that must be followed when naming identifiers:

  • The identifier can not be a keyword. Keywords are reserved.
  • The identifier can only be composed of letters (lower or upper case), numbers, and the underscore character. That means the name can not contain symbols (except the underscore) nor whitespace (spaces or tabs).
  • The identifier must begin with a letter (lower or upper case) or an underscore. It can not start with a number.
  • C++ is case sensitive, and thus distinguishes between lower and upper case letters. nvalue is different than nValue is different than NVALUE.

Identifier naming best practices

Now that you know how you can name a variable, let’s talk about how you should name a variable (or function).

First, it is a convention in C++ that variable names should begin with a lowercase letter. If the variable name is one word, the whole thing should be written in lowercase letters.

Most often, functions names are also started with a lowercase letter (though there’s some disagreement on this point). We’ll follow this convention, since function main (which all programs must have) starts with a lowercase letter, as do all of the functions in the C++ standard library.

Identifier names that start with a capital letter are typically used for user-defined types (such as structs, classes, and enumerations, all of which we will cover later).

If the variable or function name is multi-word, there are two common conventions: separated by underscores, or intercapped (sometimes called CamelCase, since the capital letters stick up like the humps on a camel).

In this tutorial, we will typically use the intercapped approach because it’s easier to read (it’s easy to mistake an underscore for a space in dense blocks of code). But it’s common to see either -- the C++ standard library uses the underscore method for both variables and functions. Sometimes you’ll see a mix of the two: underscores used for variables and intercaps used for functions.

It’s worth noting that if you’re working in someone else’s code, it’s generally considered better to match the style of the code you are working in than to rigidly follow the naming conventions laid out above.

Best practice

Adopt the style conventions of the program you’re working in. Use best practices if its your program.

Second, you should avoid naming your identifiers starting with an underscore, as these names are typically reserved for OS, library, and/or compiler use.

Third, and this is perhaps the most important rule of all, give your identifiers names that actually describe what they are. It is typical for inexperienced programmers to make variable names as short as possible, either to save on typing or because they figure the meaning is obvious. This is almost always a mistake. Ideally, variables should be named in a way that would help someone who has no idea what your code does be able to figure it out as quickly as possible. In 3 months, when you look at your program again, you’ll have forgotten how it works, and you’ll thank yourself for picking variable names that make sense. The more complex the code the variable is being used in, the better name it should have.

int ccount Bad What does the c before “count” stand for?
int customerCount Good Clear what we’re counting
int i Bad* Generally bad unless use is trivial or temporary, such as loop variables
int index Either Okay if obvious what we’re indexing
int totalScore Good Descriptive
int _count Bad Do not start variable names with underscore
int count Either Okay if obvious what we’re counting
int data Bad What kind of data?
int value1, value2 Either Can be hard to differentiate between the two
int numberOfApples Good Descriptive
int monstersKilled Good Descriptive
int x, y Bad* Generally bad unless use is trivial, such as in trivial mathematical functions

* Note: it is okay to use trivial variable names for variables that have a trivial use, such as loop variables, or trivial mathematical functions.

Fourth, a clarifying comment can go a long way. For example, say we’ve declared a variable named numberOfChars that is supposed to store the number of characters in a piece of text. Does the text “Hello World!” have 10, 11, or 12 characters? It depends on whether we’re including whitespace or punctuation. Rather than naming the variable numberOfCharsIncludingWhitespaceAndPunctuation, which is rather lengthy, a well placed comment on the declaration line should help the user figure it out:

Quiz time

Question #1


Based on how you should name a variable, indicate whether each variable name is correct (follows convention), incorrect (does not follow convention), or invalid (will not compile), and why.

int sum;
Show Solution

int _apples;
Show Solution

int VALUE;
Show Solution

int my variable name;
Show Solution

int TotalCustomers;
Show Solution

int void;
Show Solution

int numFruit;
Show Solution

int 3some;
Show Solution

int meters_of_pipe;
Show Solution


1.8 -- Introduction to literals and operators
Index
1.6 -- Uninitialized variables and undefined behaviors

34 comments to 1.7 — Keywords and naming identifiers

  • Alam

    my question is that why we use hungaraian notation "n" in int nValue ,when we already know by "int" that the "Value" is an integer?

  • codeez

    woopsy on the formatting, where has the edit button gone???

  • codeez

    alignas continue friend register true
    alignof decltype goto reinterpret_cast try
    asm default if return typedef
    auto delete inline short typeid
    bool do int signed typename
    break double long sizeof union
    case dynamic_cast mutable static unsigned
    catch else namespace static_assert using
    char enum new static_cast virtual
    char16_t explicit noexcept struct void
    char32_t export nullptr switch volatile
    class extern operator template wchar_t
    const false private this while
    constexpr float protected thread_local
    const_cast for public throw

  • codeez

    The keywords table should be updated for C++11. It's cool you have added new chapters for the update and I totally get that you don't have time to edit every single page to match it, but I think the table at least should be updated, for reference's sake. :)

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">