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

62 comments to 1.4c — Keywords and naming identifiers

  • Farheen Anis

    number 2 in quiz is fine as it started with an underscore.
    In the rules that are mentioned above, it is written that an indentifier can begin
    with an underscore

    • The quiz is talking about how you should name a variable, not how you can name a variable legally. I reworded the question to make it more obvious that is the intention.

      While technically it is technically legal under C++ syntax to name your variables starting with an underscore, generally it’s not a good idea for several reasons:
      1) It’s harder to read.
      2) Variables starting with underscores (usually a double underscore) are typically used to denote variables used by system libraries.

  • Argon

    Naming conventions are *SO* important.
    Before beginning a bigger project one should clearly define how one are going to build up variable names.
    If one have a clear definition of this, reading code are so much easy, tidy and so on.

    I.e.:

    Bad:

    type tNameChar
    type tAgeChar
    type tCharHomePhone
    type tCharWorkPhone

    Better:

    type tCharName
    type tCharAge
    type tCharPhoneHome
    type tCharPhoneWork

    Thank you for great tutorial.

  • Steve

    lol @ quiz question 8.
    3some.
    You’re very slick, Alex. 😉

  • wrong:

    right:

    Check the comment in this code ^^

  • JD

    Right on… I HATE when people type like that!

  • Gabrola

    Well you stated that an identifier shouldn’t begin with a capital letter right?
    On 1.11, the Comprehensive Quiz, your function identifiers were beginning in capital letters.

    I also did it that way before reaching this part of the tutorial and I didn’t get any compile errors!

    • Alex

      Looks like I broke my own rule. 🙂 It’s fixed now.

      Starting variable or function names with a capital letter is valid C++, and so the compiler will accept it. It’s only by convention that we don’t do this.

  • PReinie

    How about acronymns in variable names? Should they be lower case (or lower case following the first character?

    In the above tutorial statement extraction: “numberOfCharsIncludingWhitespaceAndPunctuation, which is rather lengthy”, could an acronym be used… “numberOfASCIIChars” (except ASCII may include more than intended)?

    Even “numberOfAsciiChars” would be good and follow the suggested convention, but do we violate acronym naming conventions? (Acronyms are often upper case to differentiate them from “real” words.)

    • rameye

      In my experience the less capital letters in an identifier the more readable it is.

      To keep the acronymn capitalized perhaps this would be better: numberOf_ASCII_Chars

  • captain119

    “The identifier must begin with a letter or an underscore. It can not start with a number.”
    Why is number 2 is marked as wrong if it said the tutorial that it must begin with a letter or an underscore?

    • rameye

      Difference between “can be” and “should be”. Both cases were mixed into the quiz. But “should be” takes priority in the answers.

  • 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. 🙂

  • Farhad

    thank you for the useful website alex.!!

  • Paulo

    I Loled soooo HARD at this:

    Great guide btw. You have remarkable teaching qualities! I'm glad i found this website.

    Congrats!

  • Loganathan

    All the C++ programs should have a function named main. But main is not a keyword. Any reason behind this?

    • Alex

      My best guess is that keywords can’t be used for function names. So if main were a keyword, you wouldn’t be able to use it as a function name. Then you’d be in quite the pickle.

  • Confused about the function named main. how does the computer know where to start a cpp program if not at the function named main? I thought all cpp programs had to have this.

    • Alex

      C++ programs always start at function main(), and all C++ programs must have this function. What made you think otherwise?

    • Alex, Loganathan said all c++ programs SHOULD have the main function, and questioned why main was not a key word. You responded with this
      "My best guess is that keywords can’t be used for function names. So if main were a keyword, you wouldn’t be able to use it as a function name. Then you’d be in quite the pickle."
      So I though wait, they don’t HAVE to have a function called main.  My bad! Thanks for a great, great tutorial and your help. Awesome!

  • Winnie33

    Alex, i just wanted to say your lessons are amazing.
    They are well written, with lots of examples to make sure the reader understands it fully.
    (A thing you don’t see with most course sites :))
    You must have put a lot of time in these explanations, and I really appreciate it.
    Glad you exist.
    -winnie33

    btw this is just genius xD

  • Descaii

    I disagree with some of this, it is an OPINION that you need to use variables with the first letter lower case, or  camelCase, a person can name their variables any way they want, it doesn’t matter what other people like to read. You should at least mention that making a variable with the first letter capitalized will not make an error or any real issue with their code, and that this is just suggested.

    • Alex

      I updated the article to make it clearer that identifier names can use both lower or upper case letters.

      The article already makes it sufficiently clear what C++ requires and what is convention. You are always free to not follow convention, though doing so is of questionable benefit.

  • siddhesh amrale

    One thing is wrong . Identifiers can be named with uppercase first letter.

    update it ..
    and also  add donate feature so ppl can donate you for good work.thanks anyway!

    • Alex

      From a syntax standpoint, you are correct that C++ will allow variables to start with either a lower case or upper case letter (or an underscore).

      However, it is convention that variable names start only with a lower case letter, and we advise that you follow this convention. Otherwise, anybody who views your code may be confused about why you are not following convention.

      There is a donation link in the Support LearnCpp section of the website.

  • Sam Tan

    I have a question regarding using the _ character at the beginnings of variable names. There have been a few occasions where I have seen someone begin the name of a private variable with an _. Is this an acceptable naming convention or not?

    • Alex

      Some developers use an underscore prefix to denote that a variable is private to a class. However, I strongly do not recommend this practice, as variable names starting with an underscore or double underscore are typically reserved for library implementations.

      Personally, I start my private member variables with the prefix “m_” (m for member).

  • Wraith

    Good day sir.

    Just noticed, when you cited the rules for identifiers, it stated that "identifiers must begin with a letter (lower case or UPPER case)."

    Yet in the examples you shown, making a variable starting with an upper case letter is incorrect.

    Am I missing something? Or is just a mistake?

    Thank you. And I love the tutorials by the way.

  • bobz

    I am confused regarding "main"; it must be neither a keyword nor a user-defined function, right?  Is there something that you would call it if it is neither keyword nor user-defined?

    BTW this business of comments and conventions ring very true to electronic circuit design also.  You have no idea how many times I have looked at some work which I did months ago (or maybe even weeks ago).  In many cases I have built and tested; confirmed that it works as intended.  But I go back and look at my drawing and wonder how the heck that is supposed to work?  My wife thinks I am going senile.  🙁  I have been doing this for many years.

    So without being a programmer (at least not yet) I can say: Do not doubt Alex’s wisdom regarding commenting and naming conventions.  If you really get into programming, you will be glad you did.  (Unless you have a great memory and like to write mysterious code.  But do not expect to get hired.)

    Wraith: IMHO it is more than just manner and etiquette. It is a matter of saving yourself and others a lot of difficulty down the road.

    • Alex

      main is not a keyword because keywords can’t be used for function names.

      main is a user-defined function, actually (because you get to define what it does). However, it has been predeclared by the compiler (the compiler sets the name and parameters that it must have). I talk about the difference between defined vs declared in a few lessons.

      Main unique in this regard.

  • bobz

    Thanks again, Alex.

    BobZ

  • david coggins

    HI THANKS FOR THE GREAT LESSONS..
    Sorry for the caps ,im at the back of the class you might not hear me..

  • Anurag

    Hi Alex,

    Wonderful tutorial, and absolutely loving it. I have a question, I have used C++ for MS DOS environment, using turbo C IDE. In that, I could see the list of header files from Help menu. Also could see all the functions, their syntaxes etc. How can I do the same with these modern IDE. I have eclipse, and codelite and Netbeans 8.0.2.

    I have tried searching google for it, but all it shows is how to find list of functions and header files used in the given program, from navigation panel. I want the whole list, which I was able to see from turbo C. I can see the header files from cygwin folder, but I want to see it from inside the IDE.

    Your help/answer would be highly appreciated

    • Alex

      Sorry, I’m afraid I can’t help you with this one. Any documentation related functionality around language features is really up to the individual IDE to provide or Sounds like Turbo C was pretty good in that regard. I suspect most other IDEs are not.

  • Devashish

    Quiz solution #6

    “Void is a keyword”

    “Void” should be “void”

  • Jacob

    Number 7 in the quiz doesn’t follow convention and should throw a compile error since it starts with a number.

  • Jens Larsen

    I would say number Number 7 in the quiz "nAngle" is BAD.

    It is like:
    int ccount    Bad    Nobody knows what a ccount is

    What is n? It is only acceptable if it is used in an obvious way.
    n can be:
    - number of angles, but should be called "numberOfAngles" instead
    - the n’th angle
    - a random letter because the variable angle is already taken (Yes, I have seen that before)

  • I know I might sound silly but just a question- Are keywords also stored in a header file like inbuilt functions?

  • Luke

    int VaLuE; // incorrect (see your psychiatrist) 😉 i really like that you make this tutorial really easy to understand and have good time learning it.
    this one is very funny
    thank you for this awesome tutorial

  • Domenic D

    I would like to leave you a thank you for taking the time to create and maintain this site. I appreciate it a lot.
    When I started to learn C++ I thought it would be easier than it was. I believe it was my impatience or the previous language I use to use which was Visual Basic, however that was over a decade ago. I believe I lost most of the stuff I have learned. Trying all the other online courses seem to address the impatience however I would always reach a point where the material stopped being absorbed.

    I have been taking my time while going through your course and most of it is sticking so far. So I will continue along slowly while considering it was all possible due to your efforts which I will say I appreciate again as it is deserved.

    No need to respond as I just feel it is necessary to say when people do good work.

    PS I disabled adblocker for your site and actually checked out some of your sponsors. Hopefully one day I could take advantage of their services.

  • Darren

    I would disagree about *always* starting an identifier with a lower-case letter. I use the convention of naming variables using underscore separated lower-case names for variables e.g. ‘scale_factor’; camel-case starting with a lower-case character for function names e.g. ‘fullSolve’; and camel-case starting with an UPPER-CASE for class names e.g ‘RootSearch’. That way I know what the identifier is referring to when I come to use it later on in the code. I did play around with adding single characters to the beginning of variable names to show what type they represented, e.g. ‘d’ for double, ‘f’ for float, ‘i’ for int and so on with an additional ‘p’ for pointer variables, but found my code less readable (I think this is called Hungarian style). I do use an ‘m_’ to represent data members (variables) of a class as this is useful when writing the implementation of a class separate to its interface.

    Essentially the naming style is important to code readability, however I would say that consistency is more important than the style itself; the style you choose to adopt is personal to you if coding as a hobby, or will be set by the company for which you work (and its usually sensible practice not to upset those who pay your wage).

    • Alex

      Thanks for the additional thoughts. Unless I’ve misspoken somewhere (and please point out if I did so I can correct it), I’ve only indicated that variable and function names should start with a lower case letter, not all identifiers. Class names do typically start with an upper case letter, which I point out much later in the tutorials once I explain what a class is. I used to recommend Hungarian notation, because it does help avoid some potentially stupid mistakes (like doing integer divisions) but agree that it came at the cost of general comprehension.

      I agree that consistency is maybe more important than anything. I’ll add a comment about that into the lesson.

  • Elie

    Quiz -> number 8 … whoever wrote this is dirty minded ;D

  • 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.

  • Roua

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

    Age
    !ex
    R79J
    Totaiincome
    __Invalid

  • 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…

  • 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.

Leave a Comment

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