Search

1.4c — Keywords and naming identifiers

Keywords

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

alignas **
alignof **
and
and_eq
asm
auto
bitand
bitor
bool *
break
case
catch
char
char16_t **
char32_t **
class
compl
const
constexpr **
const_cast *
continue
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 *
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

* These 15 keywords were added in C++98. Some older reference books or material may omit these.
** These 9 keywords were added in C++11. If your compiler is not C++11 compliant, 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.

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

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

Identifier naming rules

The name of a variable, function, type, or other kind of object in C++ 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++ distinguishes between lower and upper case letters. nvalue is different than nValue is different than NVALUE.

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.

Generally, functions are also started with a lowercase letter (though there’s some disagreement on this point). We’ll start ours with lower case letters for consistency, since 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 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.

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 Nobody knows what a ccount is
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

Pick which variables are improperly named according to standard conventions (ie. how you should name a variable) and indicate why.

1) int sum;
2) int _apples;
3) int VALUE;
4) int my variable name;
5) int TotalCustomers;
6) int void;
7) int numFruit;
8) int 3some;
9) int meters_of_pipe;

Show Solution

1.4d -- A first look at local scope
Index
1.4b -- Why functions are useful, and how to use them effectively

99 comments to 1.4c — Keywords and naming identifiers

  • mondomole

    This has been a bit distracting…

    "can not" ought to be "cannot"

    These lessons are absolutely fantastic! Very well written!

  • Azure

    5 is also following the rules, no?

  • William

    Do source files follow the same conventions as identifiers?

    Would this:

    Be preferred over the following:

    • Alex

      I’m not aware of any consistent recommendations in regards to filenames (other than use .cpp and .h as the extensions). Google recommends using all lower case, with dashes or underscores to separate words. Personally, I prefer capitalizing the first letter of each word in the name.

  • Ritesh Kumar

    Hi, I am learning C++ for my OpenSees project and find this site very handy to start with. The person clearly got funny bones here. This one made my day 🙂

    int VaLuE; // incorrect (see your psychiatrist) 😉

  • Fantastic web site. Penty οf helpful info Һere. I am sending іt to seveгal pals aans also sharing in delicious.

    Ꭺnd оf course, thannk yoou for your sweat!

  • coder_king

    3some 😛 HAHAH

  • Jeremy

    Seems there are 4 distinct styles, though no one seems to know where each came from, exactly:

    SCREAMING_SNAKE_CASE
    snake_case
    CamelCase (or PascalCase, or UpperCamelCase)
    camelCase (or lowerCamelCase)

    The level of disagreement on which style should be used for which type of identifier seems high enough to start WWIII.
    And most people seem to despise the Google Style Guide (https://google.github.io/styleguide/cppguide.html).
    We live in a quirky world.

  • My dear c++ Teacher,
    Please let me ask you something of the many I do not understand. At
    http://en.cppreference.com/w/cpp/language/identifiers
    there is a list of Unicode character ranges that are allowed in identifiers. What does it mean?
    With regards and friendship.

    • Alex

      Since C++ tends to be English-language and ASCII-centric (all of the keywords are English words), most people name their variables and functions using standard ASCII characters. However, there are languages that use other symbols (such as Russian). To better support non-English languages, C++ allows you to name your variables and functions using unicode characters, as long as they fall within the accepted unicode range.

      This means you can do things like, “int Ж = 5;”.

  • Felipe

    isn’t it generally a good practice to name a variable if it’s static in capital letters?

  • My dear c++ Teacher,
    Please let me express my difficulty in understanding your comment:

    How is it possible something incorrect be valid?
    With regards and friendship.

    • Alex

      Valid in that the C++ compiler will accept it, but incorrect according to best practices.

      • My dear c++ Teacher,
        Please let me say that best practices have exceptions as every rule have.
        For example, real part of complex number is denoted by "Re" and imaginary’s by "Im". Then best names for corresponding variables are "Re" and "Im".
        With regards and friendship.

      • My dear c++ Teacher,
        Please let me say more examples of exceptions from your rule. Suppose I want countries names be variables names. Then what should variable name for your country be? usa, uSa, or USA?
        Or, if you give variables names, names of USA Presidents, what do you will prefer?
        1. Washington or washington?
        2. Lincoln or lincoln?
        3. Roosevelt or roosevelt?
        4. Kennedy or kennedy?
        last but not least
        5. Obama or obama?
        With regards and friendship.

        • Alex

          Personally, I’d use lower case for everything: usa, washington, etc… Consistency leads to more efficiency, comprehension, and fewer errors.

          • My dear c++ Teacher,
            Please let me disagree on this point. I can not give variable name greece, for, it is my country, nor france for is the country I live. Also I can not use variables names, tsipras or hollande. I should use, Greece, France, Tsipras, Hollande.
            With regards and friendship.

            • Alex

              Let’s not confuse “can not” with “will not”. You _can_ use lower case letters for variables holding country names, and you _should_ (as that is the common convention). If you choose not to do so for some other reason, then you _won’t_, and that’s your personal choice.

              For what it’s worth, capitalizing proper names is a spoken language convention. When you write code, you really should follow coding conventions, not speaking conventions.

  • My dear c++ Teacher,
    Please let me take position at disagreement side on that "Generally, functions are also started with a lowercase letter …".
    Compilers online execute following program without complain.

    With regards and friendship.

    • Alex

      C++ does not require functions to start with a lower case letter, but it is a good idea. It is up to you if you want to follow best coding practices or not.

  • My dear c++ Teacher,
    Please let me my first comment on this section:
    You state "First, it is a convention in C++ that variable names should begin with a lowercase letter".
    I do not understand (am Greek living in France) what you mean by "convention" but by trial I found that compilers on line
    1. https://www.tutorialspoint.com/compile_cpp_online.php
    2. http://cpp.sh/
    3. https://www.tutorialspoint.com/cplusplus/
    4. http://rextester.com/l/cpp_online_compiler_visual
    run fine following program without throw any warning.

    With regards and friendship.

    • Alex

      “Convention” means “something that people commonly do”.

      In this case, C++ doesn’t require that variables start with a lower case letter (which is why your program compiles), but most people do so because it’s a good idea.

  • My dear c++ Teacher,
    Please let me ask my first question about this section.
    In subsection "Keywords" you present keywords through c++14. Also by one * those added in c++98 and by two ** those in c++11. My question:
    In c++14 no one added?
    With regards and friendship.

  • Tim

    When I first starting learning to code years ago the naming convention taught to me was prefixing with camelCase. (Although it wasn’t called camelCase back then.)

    For example:

    (Integer variable)

    (String variable)

    I don’t see that type of naming convention at all anymore. I really liked the fact that it told you what type of object it was right in the name. Is there a reason(s) this naming convention fell out of favor?

    • Alex

      The type prefixing you’re talking about is generally referred to is generally called “Hungarian Notation”, and I used to teach it myself. But as I’ve been updating the lessons, I’ve moved away from it in accordance with modern best practices. Hungarian notation doesn’t add a lot of value in strongly-typed languages like C++, because it repeats information that can already be easily gleaned from the compiler. It makes naming more complicated, and making changing a variable’s type painful (e.g. if you change a short to an int, now you have to rename all instances of the variable).

      Better is to add prefixes that impart information that can’t be easily gleaned, like whether a position is absolute or relative, or whether a temperature is Celsius, Fahrenheit, or Kelvin.

      • Tim

        Thanks for the reply. I don’t really understand why it adds less value to a strongly-typed language (or maybe I don’t truly understand what a strongly-typed language is.)

        The compiler isn’t going to care what I call an object I have created. If I try to put a number into an integer variable named myVariable, the compiler is going to be OK with that. On the other hand if I try to put a string into that variable the compiler is going to error out, but I won’t know that until I try to compile. Now I need to go through the error log to find out were the error is and correct it. If I named it intVariable I would know it before I tried to compile. The whole point of naming objects is to make it easier for the person reading the code to understand what that piece of code is and does, not the compiler.

        Most of my coding experience is in batch files, VB 6, VB script, and a little (and I mean very little) Java. In some of my VB6 projects the prefixing with variable type saved me a lot of time and made it much easier to remember what I was doing 6 months after doing it. I am also a hobby coder, no formal coding education, so that may be part of the problem with me understanding.

        Again, thanks for the reply. And thanks for this website. I tried learning C++ several times before and this website has done more for me than everything else I have tried before it.

        • Alex

          C++ forces you to declare the type of your variables, and does all kinds of checking to ensure you’re not doing things that are type-inappropriate. When you do something like this:

          prefixing your variable with “int” is redundant, you just declared that it was an int, so why put it in the name too? If you’re looking at variables that weren’t just defined, most modern IDEs will show you the type on hover. So encoding it in the name is mostly redundant. Many people feel putting type prefixes on your variables does not make your code easier to read or understand -- that it just adds needless clutter.

          Consider a weakly typed language like PHP. In a language like that, you can do this:

          In a language like that, where variables can hold different types, being more explicit about the type of value your variable is intended to hold can be useful, because the type is set (and can be changed) at runtime.

          There’s a fair good discussion on the topic here on Stack Overflow. The top answer is fairly comprehensive and understandable.

  • Vlad

    i downloaded code::blocks but i got the 98 version, the version from their website is not completing the download, i don’t know why, is there any way i can find the latest version somewhere else? and do you have an idea about the microsoft IDE … it says to me that it does not work on windows 7, so which windows? 8 and above?

  • Garry E

    Alex:
    It’s interesting to note that C has only 32 keywords compared to 73 as shown at the top of this tutorial or
    perhaps 90 found on the web at cppreference.com. I imagine the ‘how come?’ will become clear to me as I proceed through your incredibly well written nybbles of text explaining the C++ programming language.

    • Alex

      I was missing 11 keywords that work as substitutes for operators. I’ve never seen anybody use these, but they are valid keywords so I’ve added them to the table.

      The other keywords listed on cppreference.com are part of experimental features that haven’t been formally accepted into the C++ specification yet.

  • ANAND RAVAL

    I am beginner..
    I find your tutorials very interesting and easy to learn so far….
    I hope that this learning enable me to be able to write my own projects for some extra income some day…


    Thanks for great work…

  • Roua

    Help me
    Which if the following identifiers are right and which are wrong

    Age
    !ex
    R79J
    Totaiincome
    __Invalid

    • My dear c++ Teacher,
      Please let me answer above question and correct me where I’m wrong.
      1. Age, R79J, Totaiincome (or Totalincome) are valid but not recommended, because first letter is capital.
      2. _Invalid is valid but not recommended for begins with underscore.
      3. !ex is invalid for begins with no letter or underscore.
      Tanks in advance.
      With regards and friendship.

  • John

    This code compiles without errors using g++ test.cpp

    test.cpp

    So why isn’t main a reserved keyword?

    • Alex

      Keywords can’t be used as function names.

      • John

        Is it correct to say that main() is a built in function, and that main is a reserved keyword in addition to the table you started this section with?

        If this is the case, are there any additional built in functions? The trigonometric functions, e.g. sin and cos, are not built in, they require <math> to work.

        • Alex

          No, and no. main() is a user-defined function that just happens to be required. It is not a reserved keyword (as evidenced by the fact that you can create a variable named main).

          C++ does not have any built-in functions. But the C++ library contains tons of predefined functions (such as sin and cos) that you can include in your programs if you want.

Leave a Comment

Put C++ code inside [code][/code] tags to use the syntax highlighter