1.7 — Keywords and naming identifiers


C++ reserves a set of 92 words (as of C++20) 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++20):

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

The keywords marked (C++20) were added in C++20. If your compiler is not C++20 compliant (or does have C++20 functionality, but it’s turned off by default), these keywords may not be functional.

C++ also defines special identifiers: override, final, import, and module. 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, function 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: words separated by underscores, called snake_case, 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

When working in an existing program, use the conventions of that program (even if they don’t conform to modern best practices). Use modern best practices when you’re writing new programs.

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, your identifiers should make clear what the value they are holding means (particularly if the units aren’t obvious). Identifiers 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.

However, giving a trivial variable an overly complex name impedes overall understanding of what the program is doing almost as much as giving a widely used identifier an inadequate name. Therefore, a good rule of thumb is to make the length of an identifier proportional to how widely it is used. An identifier with a trivial use can have a short name (e.g. such as i). An identifier that is used more broadly (e.g. a function that is called from many different places in a program) should have a longer and more descriptive name (e.g. instead of open, try openFileOnDisk).

int ccount Bad What does the c before “count” stand for?
int customerCount Good Clear what we’re counting
int i Either Okay if use is trivial, bad otherwise
int index Either Okay if obvious what we’re indexing
int totalScore Either Okay if there’s only one thing being scored, otherwise too ambiguous
int _count Bad Do not start names with underscore
int count Either Okay if obvious what we’re counting
int data Bad What kind of data?
int time Bad Is this in seconds, minutes, or hours?
int minutesElapsed Good Descriptive
int value1, value2 Either Can be hard to differentiate between the two
int numApples Good Descriptive
int monstersKilled Good Descriptive
int x, y Either Okay if use is trivial, bad otherwise

In any case, avoid abbreviations. Although they reduce the time you need to write your code, they make your code harder to read. Even if the abbreviation is unambiguous, it takes the reader a moment to figure out what you meant. Code is read more often than it is written, the time you saved while writing the code is time that every reader, including the future you, wastes when reading it. If you’re looking to write code faster, use your editor’s auto-complete feature.

Finally, 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; // assume it’s obvious what we’re summing
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 -- Whitespace and basic formatting
1.6 -- Uninitialized variables and undefined behavior

230 comments to 1.7 — Keywords and naming identifiers

  • Waldo Lemmer

    Section "Identifier naming best practices", after green block:
    - 2nd paragraph:

    > (particularly if the units **isn’t** obvious)

    - 3rd paragraph:

    > thumb is to make the length of **a** identifier

  • Manuel Calzadillas

    Great lesson
    I'm sure everyone that actually finish this cpp course will become an incredible programmer.
    "You don't have to be great to get started, but you have to get started to be great"

  • Julian

    Why would you ever name your variable 3some? lol

  • Naeio

    If you have a good IDE, does a long name really slows you down?
    Personally, what annoys me about long names is the loooonngggg lines you might write :

    Ok my example is a bit extreme, and you can use objects just to have `point1` and `point2`, but the point I wanna make is that reading a 200 char line is annoying, and sometimes abbreviation can be useful in my opinion, like `pt1_coordx` but they need to be quickly understandable.

    • nascardriver

      The problem aren't the long names, the problem is that `are_points_nearby` has too many parameter.
      I get your point, but if you have good types and functions, you won't get such long lines.

    • KoCa

      it will be covered later probably, but intead of point1_coordonate_x
      you may make struc that is point and  has x and y in it then you pass only instance of that struc to your function as point1 and another one as point2 (or even array of them)

      • Naeio

        @nascardriver @KoCa
        True I could use a struct/object, I just wanted to make on the fly a function that would take 4 arguments. 4 is not a lot IMHO. And my point is that the time it takes to type it is not a big deal, and it's more about the readibility that we need to think

  • Patrick

    3some - what's wrong with this?

    • Zach

      It is part of the C++ standard - and the standard for most programming languages to not allow you to start an identifier with a number. This is generally due to how the compiler works.

      For instance:

      int a = 2;
      int 3 = 5;
      int c = 3 * a;
      std::cout << c;

      The compiler would have trouble reading your multiplier: Does the user mean to use the identifier 3, or does the user mean to use the actual value of 3? Because 6 and 15 are not the same. There are probably ways to build a compiler to deal with this - but it's better to just not have to deal wit hit in the first place.

    • Burfed

      Nothing is wrong - threesomes are generally very enjoyable!

  • yeokaiwei

    int 3some;

    It would be nice to have a Bad example of naming variables in the table that starts with a number.

    Thank you for the tutorial.

  • yeokaiwei

    int sum; // assume it’s obvious what we’re summing
    Show Solution

    int _apples;
    Show Solution

    The quiz does not show initialization.

  • yeokaiwei

    Contradictory instructions. Instead of spelling "integer", you use "int". Instead of spelling "character_out", you use "cout".

  • Asraful Islam

    where was define gone?

  • Manuel

    Hello! I have several questions that are somewhat silly, but I've been asking myself since I started with the tutorials.
    1.- Do I need to understand everything 100%?
    2.- Any advice that can help me understand everything a little better?

    • nascardriver

      1.- No. You'll start to understand it once you start to use it.
      2.- Do this quizzes, post your solutions in the comments for review. Ask questions. If you can think of a project that you'd enjoy working on, start the project and do it alongside the lessons to stay motivated and apply what you learned.

      • .Exodia


        what kind of project would you recommend? I have no clue.

        It shouldnt be too big but as you said, one i can use what i learned on.


        • nascardriver

          I played a lot of video games when I learned C++, so I wrote cheats and tools for those games. I had a use for them, that kept me motivated to keep on learning.

          Try thinking of something that you'll actually use, and you won't stop learning.

  • Aashish

    Some correction needs to be done:

    Rule: The identifier must begin with a letter (lower or upper case) or an underscore. It can not start with a number.

    Case: int VALUE; // incorrect (should start with lower case letter)
    Case: int _apples;
          Incorrect -- variable names should not start with an underscore.
          int VALUE;
          Incorrect -- variable names should start with a lower case letter.

  • Matteo

    Hey, Alex. Thanks so much for writing this guide. I've actually started a Discord server (or guild) dedicated to working through this guide and have 100+ people in here helping each-other out. I saw in these comments people were interested.

    If you wanted to join the server (and can prove it's you) I can give you full administrator permissions and perhaps you can even add the server to your guide. If not please feel welcome to come hang out anyways - that goes for anyone else reading this as well!

  • Cerezas

    One best practice for naming identifiers may have been forgot.
    - Avoid very close identifiers, especially for the same type.

    Consequently, names in their plural form should be reserved for collection identifiers.

    I come from the first exercise of lesson "S.4.5" where plural is used in the question but the solution identifiers are singular.

Leave a Comment

Put all code inside code tags: [code]your code here[/code]