Lesson 4 +25 XP

Tokens, Keywords, Identifiers & Constants

Tokens, Keywords, Identifiers & Constants

The compiler reads a C++ program as a stream of characters and groups them into tokens: the smallest individual units of a program, like words in a sentence. This lesson covers the five kinds of tokens and looks closely at keywords, identifiers and constants.

1. Tokens

TokenWhat it isExamples
Keywordsreserved words with a fixed meaningint, class, return, virtual
Identifiersnames chosen by the programmertotal, Student, getData
Constants (literals)fixed values25, 3.14, 'A', "Hello"
Stringssequences of characters in double quotes"C++"
Operatorssymbols that act on operands+, <<, ::, new
Punctuators (separators)symbols that structure the code; , { } ( ) [ ] #

The statement int total = price + 50; has seven tokens: int, total, =, price, +, 50, ;.

2. Keywords

Keywords are reserved identifiers with a predefined meaning. They cannot be used as names of variables, functions or classes. C++98 has 63 keywords: the 32 keywords of C plus 31 more.

GroupKeywords
From C (32)auto break case char const continue default do double else enum extern float for goto if int long register return short signed sizeof static struct switch typedef union unsigned void volatile while
Classes and objectsclass private protected public friend this virtual inline operator explicit mutable
Memorynew delete
Exceptionstry catch throw
Templatestemplate typename export
Namespacesnamespace using
Types and castsbool true false wchar_t typeid const_cast dynamic_cast reinterpret_cast static_cast
Otherasm

C++ also reserves alternative spellings for some operators: and, or, not, xor, bitand, bitor, compl, and_eq, or_eq, xor_eq, not_eq.

3. Identifiers

Identifiers are the names of variables, functions, arrays, classes and so on. The rules:

  1. Only letters, digits and the underscore may be used.
  2. The first character must be a letter or an underscore, never a digit.
  3. Upper and lower case are distinct: Total and total are different names.
  4. A keyword cannot be used as an identifier.
  5. C++ places no limit on the length of an identifier (ANSI C kept only the first 32 characters significant).
NameValid?Reason
marks2✅letters then a digit
_count✅may start with an underscore (but such names are best left to the library)
totalMarks✅camel case is common in C++
2ndRoll❌starts with a digit
total marks❌contains a space
float❌a keyword
roll-no❌- is not allowed
$amount❌$ is not allowed in standard C++

4. Constants (Literals)

Constants are fixed values that do not change while the program runs.

KindExamplesNotes
Integer123, -45, 0decimal
037octal (leading 0) = 31
0x1Fhexadecimal (leading 0x) = 31
40000L, 25U, 7ULsuffixes: L = long, U = unsigned
Floating point3.14, -0.5, 2.5e32.5e3 means 2.5 × 103; 3.14f is a float, 3.14L a long double
Character

' | single quotes; type char in C++ (it was int` in C) |

Escape sequences are character constants written with a backslash:

EscapeMeaningEscapeMeaning

| new line | \\` | backslash |

Symbolic constants

A named constant is clearer and safer than a bare number. C++ offers two ways (and the C-style macro):

WayExampleNotes
const qualifierconst int MAX = 100;has a type and a scope; preferred in C++; must be initialised
enumenum Color { RED, GREEN, BLUE };a set of named integer constants: 0, 1, 2
#define macro#define PI 3.14159text replacement by the preprocessor; no type checking

In C++ a const at file scope is local to its file by default (internal linkage); in C it is global. Write extern const to share it across files.

C++
#include <iostream>
using namespace std;

#define PI 3.14159 // macro: plain text replacement
const int MAX = 5; // typed constant
enum Day {
    MON = 1,
    TUE,
    WED
}; // TUE = 2, WED = 3

int main() {
    int octal = 037, hexa = 0x1F;
    char c = 'A';
    bool ok = true;
    cout << "MAX = " << MAX << ", PI = " << PI << endl;
    cout << "037 = " << octal << ", 0x1F = " << hexa << endl;
    cout << "WED = " << WED << endl;
    cout << "char " << c << " has code " << (int)c << endl;
    cout << "ok = " << ok << ", 2.5e3 = " << 2.5e3 << endl;
    cout << "Tab:\t|" << endl;
    // MAX = 10;                       // error: assignment of read-only variable
    return 0;
}

Output:

OUTPUT
MAX = 5, PI = 3.14159
037 = 31, 0x1F = 31
WED = 3
char A has code 65
ok = 1, 2.5e3 = 2500
Tab:	|

Note that cout prints a bool as 1 or 0 unless the boolalpha manipulator is used (Unit IV).

💡 Tip

Key points to remember

  • Tokens: keywords, identifiers, constants, strings, operators, punctuators.
  • Keywords are reserved; C++98 has 63 (32 from C plus 31 new, such as class, new, virtual, try, template).
  • Identifiers: letters, digits, underscore; must not start with a digit; case-sensitive; no length limit.
  • 037 is octal, 0x1F is hex; 'A' is a char in C++.
  • Prefer const to #define: it is typed and scoped.
🎯 END-TERM EXAM PREP

📝 IPU End-Term Exam Corner (5-10 Marks)

  • Q1. What are tokens? Explain the different types of tokens in C++. (5 Marks)
  • Write: the definition, the six kinds with examples, and the seven tokens of int total = price + 50;.
  • Q2. State the rules for naming identifiers. Which of these are valid: 2ndRoll, _count, float, roll-no? (2.5 Marks)
  • Q3. What are constants? Explain the types of constants in C++, including symbolic constants. (5 Marks)
  • Write: the constants table, the escape sequences, and const vs enum vs #define.
  • Q4. Differentiate between const and #define. (2.5 Marks)