Curriculum
Course: Complete C++ Programming Course
Login

Curriculum

Complete C++ Programming Course

Text lesson

Understanding Tokens in C++

In this lesson, you will learn

  • Tokens in C++
  • Examples

 

Tokens in C++

In C++, tokens are the smallest units of a program that have a specific meaning to the compiler.

Tokens are categorized into several types, each playing a different role in the language. Here’s a detailed explanation of each type of token with examples.

TokenInC++

1. Identifiers

  • Identifiers are names given to variables, methods, classes, objects, arrays, and other program elements.
  • Identifiers must follow certain rules and conventions.

 

Rule to make identifiers in C++

The following are the rules for forming valid identifiers.

  1. An identifier can have uppercase and lowercase letters(A-Z or a-z), numbers(0-9), underscore( _ ), and dollar-sign($) characters.
  2. Identifiers must not begin with digits.
  3. It can be of any length.
  4. Keywords can’t be used for naming identifiers.
  5. Java is a case-sensitive language i.e. VALUE and value are different identifiers.

Examples: Valid identifiers

Mybooks, DATE_06_12, B1T019, AvgValue, result, $1_23_$a, _value, PRINTRESULT, _PRICE, _MY_JK_2, temp$, isAlphabet

Examples: Invalid identifiers

  1. 23Date – Invalid because Starting with a number
  2. Item-Price, yes/no, print.file – Invalid because it contains a character other than A-Z, a-z, digit, underscore( _ ), or dollar($)
  3. Print Result – Invalid because it contains whitespace.

 

Example: Identifier

#include<iostream>

int main() {
    int age = 30; // 'age' is an identifier
    std::cout << "Age: " << age << std::endl;
    return 0;
}



Identifiers: age, main, cout, variableName, etc.

 

2. Keywords

C++ keywords are reserved words that have special meanings in the language. They cannot be used as identifiers (e.g., variable names, function names) because they are fundamental to the syntax and structure of the language.

Here’s a summary table of the C++ keywords:

KeywordDescription
alignasSpecifies alignment requirements for variables or data structures.
alignofReturns the alignment requirement of a type.
andAlternative for the && operator (logical AND).
and_eqAlternative for the &= operator (bitwise AND assignment).
asmAllows embedding assembly language in C++ code.
autoAutomatically deduces the type of a variable from its initializer.
bitandAlternative for the & operator (bitwise AND).
bitorAlternative for the `
boolRepresents boolean values (true or false).
breakExits from the nearest enclosing loop or switch statement.
caseDefines a branch in a switch statement.
catchCatches exceptions thrown by a try block.
charRepresents character data.
char16_tRepresents a 16-bit wide character.
char32_tRepresents a 32-bit wide character.
classDefines a user-defined type (class).
complAlternative for the ~ operator (bitwise NOT).
constSpecifies that a variable’s value cannot be changed.
constexprSpecifies that a value or function can be evaluated at compile time.
const_castCasts away the constness of a variable.
continueSkips the rest of the current loop iteration and continues with the next iteration.
decltypeDetermines the type of an expression.
defaultSpecifies the default behavior of a function or constructor.
deleteDeallocates memory previously allocated with new.
doStarts a do-while loop.
doubleRepresents double-precision floating-point numbers.
dynamic_castSafely casts pointers or references within an inheritance hierarchy.
elseSpecifies the block of code to execute if the if condition is false.
enumDefines a set of named integer constants.
explicitSpecifies that a constructor or conversion operator should not be implicitly invoked.
exportAllows template definitions to be separated from their declarations (rarely used).
externDeclares a variable or function that is defined in another file or translation unit.
falseRepresents the boolean value false.
floatRepresents single-precision floating-point numbers.
forStarts a for loop.
friendGrants access to private and protected members of a class.
gotoTransfers control to a labeled statement.
ifSpecifies a conditional block of code.
inlineRequests the compiler to attempt to inline a function.
intRepresents integer data.
longRepresents long integer data.
mutableAllows a member of a class to be modified even if the class object is const.
namespaceDefines a scope that groups related identifiers.
newAllocates memory dynamically.
noexceptSpecifies that a function does not throw exceptions.
notAlternative for the ! operator (logical NOT).
not_eqAlternative for the != operator (not equal).
nullptrRepresents a null pointer constant.
operatorDefines or overloads operators.
orAlternative for the `
or_eqAlternative for the `
privateSpecifies private access control within a class.
protectedSpecifies protected access control within a class.
publicSpecifies public access control within a class.
registerSuggests to the compiler that a variable should be stored in a register (deprecated in C++11).
reinterpret_castPerforms a type cast between unrelated types.
returnExits from a function and optionally returns a value.
shortRepresents short integer data.
signedSpecifies signed integer types.
sizeofReturns the size of a type or object.
staticSpecifies static storage duration or linkage.
static_assertPerforms a compile-time assertion.
structDefines a user-defined type (structure).
switchDefines a multi-way branch based on the value of an expression.
templateDefines a template for functions or classes.
thisRepresents a pointer to the current object.
throwThrows an exception.
trueRepresents the boolean value true.
tryStarts a block of code to handle exceptions.
typedefDefines a new name for an existing type.
typeidRetrieves type information at runtime.
typenameSpecifies a type parameter in templates.
unionDefines a user-defined type (union).
unsignedSpecifies unsigned integer types.
usingIntroduces a name into the current scope or creates type aliases.
virtualIndicates that a function can be overridden in a derived class.
voidRepresents the absence of type or a function that does not return a value.
volatileSpecifies that a variable may be changed by external factors.
wchar_tRepresents wide character data.
whileStarts a while loop.
xorAlternative for the ^ operator (bitwise XOR).
xor_eqAlternative for the ^= operator (bitwise XOR assignment).

 

3. Constants or Literals

In C++, constants and literals are values that do not change during the execution of a program. They represent fixed data that can be used directly in code.

Here’s a detailed explanation of different types of constants and literals in C++, with examples.

ConstantsInC++

1. Integer Literals

Integer literals represent whole numbers and can be expressed in decimal, octal, or hexadecimal format.

Examples: Integer Literals

#include<iostream>

int main() {
    int decimal = 42;    // Decimal integer literal
    int octal = 052;     // Octal integer literal (base 8, prefixed with 0)
    int hexadecimal = 0x2A; // Hexadecimal integer literal (base 16, prefixed with 0x)
    
    std::cout << "Decimal: " << decimal << std::endl;
    std::cout << "Octal: " << octal << std::endl;
    std::cout << "Hexadecimal: " << hexadecimal << std::endl;

    return 0;
}


Output:

Decimal: 42
Octal: 42
Hexadecimal: 42


 

2. Floating-Point Literals

Floating-point literals represent numbers with decimal points and can be expressed in decimal or scientific notation.

Examples: Floating-Points Literals

#include<iostream>

int main() {
    float pi = 3.14159f;       // Decimal floating-point literal (float)
    double e = 2.718281828459; // Decimal floating-point literal (double)
    double scientific = 1.23e4; // Scientific notation (1.23 &times; 10^4)
    
    std::cout << "Pi: " << pi << std::endl;
    std::cout << "E: " << e << std::endl;
    std::cout << "Scientific notation: " << scientific << std::endl;

    return 0;
}


 

Output

Pi: 3.14159
E: 2.71828
Scientific notation: 12300


 

3. Character Literals

Character literals represent individual characters enclosed in single quotes.

Examples: Character Literals

#include<iostream>

int main() {
    char letter = 'A';       // Single character literal
    char digit = '7';        // Single character literal
    char newline = '\n';    // Escape sequence for newline
    char tab = '\t';        // Escape sequence for horizontal tab

    std::cout << "Letter: " << letter << std::endl;
    std::cout << "Digit: " << digit << std::endl;
    std::cout << "Newline: " << newline << "Next line" << std::endl;
    std::cout << "Tab: " << tab << "Tabbed text" << std::endl;

    return 0;
}


 

Output:

Letter: A
Digit: 7
Newline:
Next line
Tab:    Tabbed text


 

4. String Literals

String literals represent sequences of characters enclosed in double-quotes.

Examples: String Literals

#include<iostream>

int main() {
    const char* greeting = "Hello, World!"; // String literal
    const char* multiline = "This is a\nmultiline\nstring"; // String with newline characters

    std::cout << "Greeting: " << greeting << std::endl;
    std::cout << "Multiline: " << multiline << std::endl;

    return 0;
}


 

Output:

Greeting: Hello, World!
Multiline: This is a
multiline
string


 

5. Wide Character Literals

Wide character literals represent characters in wide format, enclosed in single quotes with an L prefix.

Examples: Wide Character Literals

#include<iostream>

int main() {
    wchar_t wideChar = L'汉';     // Wide character literal
    wchar_t wideString[] = L"你好"; // Wide string literal

    std::wcout << L"Wide character: " << wideChar << std::endl;
    std::wcout << L"Wide string: " << wideString << std::endl;

    return 0;
}


Output:

Wide character: 汉
Wide string: 你好



 

6. Boolean Literals

Boolean literals represent truth values and can be true or false.

Examples: Boolean Literals

#include<iostream> 

int main() {
    bool isTrue = true;   // Boolean literal true
    bool isFalse = false; // Boolean literal false

    std::cout << "isTrue: " << isTrue << std::endl;
    std::cout << "isFalse: " << isFalse << std::endl;

    return 0;
}


 

Output:

isTrue: 1
isFalse: 0



 

7. Null Pointer Literals

Null pointer literals represent a null pointer constant. In modern C++, the nullptr keyword is used.

Examples: Null Pointer Literals

#include<iostream>

int main() {
    int* ptr = nullptr; // Null pointer literal
    
    if (ptr == nullptr) {
        std::cout << "Pointer is null." << std::endl;
    }

    return 0;
}



Output:

Pointer is null.


 

Summary

  • Integer Literals: Represent whole numbers (e.g., 42, 052, 0x2A).
  • Floating-Point Literals: Represent numbers with decimal points (e.g., 3.14159, 1.23e4).
  • Character Literals: Represent individual characters (e.g., 'A', '7', '\n').
  • String Literals: Represent sequences of characters (e.g., "Hello, World!").
  • Wide Character Literals: Represent wide characters (e.g., L'汉', L"你好").
  • Boolean Literals: Represent truth values (true, false).
  • Null Pointer Literals: Represent null pointers (nullptr).

These constants and literals are fundamental in C++ programming, providing fixed values that can be used throughout your code.

 

4. Punctuation (Delimeters)

In C++, punctuation (also known as delimiters) are special symbols that help define the structure and organization of the code.

They are used to separate and group tokens, mark the end of statements, define blocks of code, and more.

Here’s a summary table of the punctuation (delimiters) used in C++ with examples:

Punctuation (Delimiter)DescriptionExample
;Terminates statements.int x = 5;
,Separates elements in a list (e.g., function arguments, variable declarations).int a = 1, b = 2;
.Accesses members of an object or class.obj.member
()Defines function calls or group expressions.foo();
{}Defines a block of code (e.g., function bodies, loops).if (x > 0) { std::cout << "Positive"; }
[]Defines arrays or accesses elements by index.int arr[10]; arr[0] = 1;

 

5. Operators

In C++, operators are symbols that perform operations on variables and values. Here is a summary table of different operators in C++ with explanations and examples:

OperatorTypeDescriptionExample
+ArithmeticAddition of two values.int sum = 5 + 3;
-ArithmeticSubtraction of one value from another.int diff = 7 - 2;
*ArithmeticMultiplication of two values.int product = 4 * 3;
/ArithmeticDivision of one value by another.int quotient = 8 / 2;
%ArithmeticModulus or remainder of division.int remainder = 5 % 2;
++IncrementIncrements the value of a variable by 1.x++;++x;
--DecrementDecrements the value of a variable by 1.x--;--x;
+UnaryUnary plus (indicates positive value, usually implicit).int positive = +5;
-UnaryUnary minus (negates a value).int negative = -5;
~BitwiseBitwise NOT (inverts bits).int result = ~5;
!LogicalLogical NOT (inverts boolean value).bool notTrue = !true;
&Bitwise / Address-ofBitwise AND or address-of operator.int* ptr = &x;int result = a & b;
``BitwiseBitwise OR operator.
^BitwiseBitwise XOR operator.int result = a ^ b;
<<Bitwise / ShiftBitwise left shift or stream insertion operator.int shifted = a << 1;std::cout << "Hello";
>>Bitwise / ShiftBitwise right shift or stream extraction operator.int shifted = a >> 1;std::cin >> x;
==RelationalEquality comparison.bool isEqual = (a == b);
!=RelationalInequality comparison.bool isNotEqual = (a != b);
<RelationalLess than comparison.bool isLess = (a < b);
>RelationalGreater than comparison.bool isGreater = (a > b);
<=RelationalLess than or equal to comparison.bool isLessEqual = (a <= b);
>=RelationalGreater than or equal to comparison.bool isGreaterEqual = (a >= b);
&&LogicalLogical AND (both conditions must be true).bool result = (a > 0 && b > 0);
` `Logical
? :Conditional (Ternary)Ternary conditional operator.int result = (a > b) ? a : b;
=AssignmentAssigns value to a variable.int x = 10;
+=AssignmentAdds value to variable and assigns the result.x += 5;x = x + 5;
-=AssignmentSubtracts value from variable and assigns the result.x -= 5;x = x - 5;
*=AssignmentMultiplies variable by value and assigns the result.x *= 5;x = x * 5;
/=AssignmentDivides variable by value and assigns the result.x /= 5;x = x / 5;
%=AssignmentApplies modulus operation and assigns the result.x %= 5;x = x % 5;
&&LogicalLogical AND.bool result = (a > 0 && b > 0);
` `Logical
,CommaSeparates expressions in statements and function parameters.int x = 5, y = 10;func(x, y);
::Scope ResolutionDefines scope for namespaces and classes.std::cout << "Hello";MyClass::member;
[]Array Access / SubscriptAccesses elements in arrays and containers.int arr[10];arr[2] = 5;
()Function Call / GroupingCalls functions and groups expressions.func();int sum = (a + b);
&Address-ofReturns the memory address of a variable.int* ptr = &x;
*Pointer DereferenceAccesses the value at the address stored in a pointer.int value = *ptr;
sizeofSizeofReturns the size of a type or variable.size_t size = sizeof(int);
typeidType IdentificationRetrieves type information at runtime.std::cout << typeid(a).name();

 

Summary

  • Arithmetic Operators: +, -, *, /, %, ++, --
  • Unary Operators: +, -, ~, !
  • Bitwise Operators: &, |, ^, ~, <<, >>
  • Logical Operators: &&, ||, !
  • Relational Operators: ==, !=, <, >, <=, >=
  • Assignment Operators: =, +=, -=, *=, /=, %=
  • Conditional (Ternary) Operator: ? :
  • Comma Operator: ,
  • Scope Resolution Operator: ::
  • Array Subscript Operator: []
  • Function Call / Grouping Operator: ()
  • Address-of / Pointer Dereference Operator: &, *
  • Sizeof Operator: sizeof
  • Type Identification Operator: typeid

These operators are fundamental to C++ programming, allowing you to perform calculations, and comparisons, and manage data and control flow in your programs.