0% found this document useful (0 votes)
12 views10 pages

Understanding C++ Tokens and Data Types

The document provides an overview of C++ programming concepts, focusing on tokens, data types, variables, and operators. It categorizes C++ tokens into keywords, identifiers, constants, operators, and punctuators, while detailing primitive, derived, and user-defined data types. Additionally, it explains variable declaration, initialization, naming rules, and various types of operators including arithmetic, relational, logical, and assignment operators.

Uploaded by

warisrampal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views10 pages

Understanding C++ Tokens and Data Types

The document provides an overview of C++ programming concepts, focusing on tokens, data types, variables, and operators. It categorizes C++ tokens into keywords, identifiers, constants, operators, and punctuators, while detailing primitive, derived, and user-defined data types. Additionally, it explains variable declaration, initialization, naming rules, and various types of operators including arithmetic, relational, logical, and assignment operators.

Uploaded by

warisrampal
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd

Notes 2

Saturday, 13 September 2025 12:47 PM

C++ Tokens

In C++, a token is the smallest unit in a program that has a meaningful interpretation for the compiler.
When we write a C++ program, the compiler breaks it into tokens before further processing (like parsing and execution).

There are several types of tokens in C++:


• Keywords:
These are reserved words that have predefined meanings in the C++ language and cannot be used as
identifiers (names for variables, functions, etc.). Examples include int, if, else, while, for, class, public, private,
etc.
• Identifiers:
These are names given by the programmer to various program elements like variables, functions, classes,
objects, etc. Identifiers must follow specific naming rules, such as starting with a letter or underscore and
consisting only of letters, digits, and underscores. C++ is case-sensitive, so myVariable and MyVariable are
considered different identifiers.
• Constants (Literals):
These are fixed values that do not change during program execution. Examples include integer literals
(e.g., 10, 100), floating-point literals (e.g., 3.14, 2.5f), character literals (e.g., 'A', 'c'), string literals (e.g., "Hello
World"), and boolean literals (e.g., true, false).
• Operators:
These are symbols that perform specific operations on operands (variables or values). Examples include
arithmetic operators (+, -, *, /, %), relational operators (==, !=, <, >, <=, >=), logical operators (&&, ||, !),
assignment operators (=, +=, -=, etc.), and increment/decrement operators (++, --).
• Punctuators (Separators/Special Characters):
These are symbols used to structure the program and separate different parts of the code. Examples include
parentheses (), curly braces {}, square brackets [], semicolon ;, comma ,, colon :, and dot ..

Data Types in C++

C++ data types classify the type of data a variable can hold, determining the
operations that can be performed on it and the memory it occupies. They are broadly
categorized into three groups:

1. Primitive (Built-in) Data Types: These are fundamental data types directly
supported by the C++ language.

1. Character Data Type (char)


The character data type is used to store a single character. The keyword
1. Primitive (Built-in) Data Types: These are fundamental data types directly
supported by the C++ language.

1. Character Data Type (char)


The character data type is used to store a single character. The keyword
used to define a character is char. Its size is 1 byte, and it stores characters
enclosed in single quotes (' '). It can generally store upto 256 characters
according to their ASCII codes.
#include <iostream>
using namespace std;

int main() {

// Character variable
char c = 'A';
cout << c;

return 0;
}

2. Integer Data Type (int)


Integer data type denotes that the given variable can store the integer
numbers. The keyword used to define integers is int. Its size is 4-bytes (for
64-bit) systems and can store numbers for binary, octal, decimal and
hexadecimal base systems in the range
from -2,147,483,648 to 2,147,483,647.

3. Boolean Data Type (bool)


The boolean data type is used to store logical values: true(1) or false(0).
The keyword used to define a boolean variable is bool. Its size is 1 byte.
#include <iostream>
using namespace std;

int main() {

// Creating a boolean variable


bool isTrue = true;
cout << isTrue;
return 0;
}
4. Floating Point Data Type (float)
Floating-point data type is used to store numbers with decimal points. The
keyword used to define floating-point numbers is float. Its size is 4 bytes (on
64-bit systems) and can store values in the range from 1.2e-38 to 3.4e+38.
#include <iostream>
using namespace std;

int main() {

// Floating point variable with a decimal value


float f = 36.5;
cout << f;

return 0;
}
5. Double Data Type (double)
The double data type is used to store decimal numbers with higher
precision. The keyword used to define double-precision floating-point
numbers is double. Its size is 8 bytes (on 64-bit systems) and can store the
values in the range from 1.7e-308 to 1.7e+308
}
5. Double Data Type (double)
The double data type is used to store decimal numbers with higher
precision. The keyword used to define double-precision floating-point
numbers is double. Its size is 8 bytes (on 64-bit systems) and can store the
values in the range from 1.7e-308 to 1.7e+308

6. Void Data Type (void)


The void data type represents the absence of value. We cannot create a
variable of void type. It is used for pointer and functions that do not return
any value using the keyword void.

Type Safety in C++


C++ is a strongly typed language. It means that all variables' data type
should be specified at the declaration, and it does not change throughout the
program. Moreover, we can only assign the values that are of the same type
as that of the variable.

2. Derived Data Types: These are constructed from primitive data types.
• Arrays: Collections of elements of the same data type stored contiguously in memory.
• Pointers: Variables that store memory addresses of other variables.
• References: Aliases or alternative names for existing variables.
• Functions: Blocks of code designed to perform a specific task.

3. User-Defined (Abstract) Data Types: These are defined by the programmer to


create custom data structures.
• class: Blueprints for creating objects, encapsulating data (member variables) and functions
(member methods).
• struct: Similar to classes but with public members by default, primarily used for grouping
related data.
• union: Allows multiple members to share the same memory location, useful for memory
optimization.
• enum (Enumeration): Defines a set of named integer constants, improving code readability.
• typedef: Creates an alias or new name for an existing data type.

Data Type Modifiers:


Modifiers like short, long, signed, and unsigned can be applied to certain data types
(e.g., int, char) to alter their size or range of values. For example, long int provides a
larger range for integers, and unsigned int stores only non-negative integers.

Variables in C++
In C++, variables are named storage locations in the computer's memory used to
hold data values. They act as containers for storing information that a program can
access and modify during its execution.

Key aspects of C++ variables:


• Declaration: Before using a variable, it must be declared. This involves specifying its data
type and a unique name (identifier). The data type determines the kind of values the
variable can store (e.g., integers, floating-point numbers, characters, booleans) and the
amount of memory it will occupy.

int age; // Declares an integer variable named 'age'


double price; // Declares a double-precision floating-point variable named 'price'
char initial; // Declares a character variable named 'initial'

• Initialization: Variables can be initialized at the time of declaration or assigned a value


type and a unique name (identifier). The data type determines the kind of values the
variable can store (e.g., integers, floating-point numbers, characters, booleans) and the
amount of memory it will occupy.

int age; // Declares an integer variable named 'age'


double price; // Declares a double-precision floating-point variable named 'price'
char initial; // Declares a character variable named 'initial'

• Initialization: Variables can be initialized at the time of declaration or assigned a value


later. Initialization means giving the variable an initial value.
int count = 10; // Declares and initializes 'count' with 10
float temperature;
temperature = 25.5f; // Assigns a value to 'temperature' later

Rules For Naming Variable


The names given to a variable are called identifiers. There are some rules for
creating these identifiers (names):
• A name can only contain letters (A-Z or a-z), digits (0-9), and underscores
(_).
• It should start with a letter or an underscore only.
• It is case sensitive.
• The name of the variable should not contain any whitespace and special
characters (i.e. #, $, %, *, etc).
• We cannot use C++ keyword (e.g. float, double, class) as a variable name.

C++ Operators

C++ operators are special symbols or keywords that perform operations on one or more operands
(values or variables).

1. Arithmetic Operators
Arithmetic Operators are used to perform arithmetic or mathematical
operations on the operands. For example, '+' is used for addition.
1. Addition, +, Adds two operands
2. Subtraction, -, Subtracts second operand from the first
3. Multiplication, *, Multiplies two operands
4. Division, /, Divides first operand by the second operand
5. Modulo Operation, %, Returns the remainder of an integer division
6. Increment, ++, Increases the value of operand by 1
7. Decrement, --, Decreases the value of operand by 1

2. Relational Operators
They are used for the comparison of the values of two operands. For
example, '>' check right operand is greater.
• Is Equal To, ==, Checks if both operands are equal
• Greater Than, >, Checks if the first operand is greater than the second
operand
• Greater Than or Equal To, >=, Checks if the first operand is greater than or
equal to the second operand
• Less Than, <, Checks if the first operand is lesser than the second operand
• Less Than or Equal To, <=, Checks if the first operand is lesser than or equal
to the second operand
• Not Equal To, !=, Checks if both operands are not equal

3. Logical Operators
They are used to combine two or more conditions or constraints or to
• Less Than or Equal To, <=, Checks if the first operand is lesser than or equal
to the second operand
• Not Equal To, !=, Checks if both operands are not equal

3. Logical Operators
They are used to combine two or more conditions or constraints or to
complement the evaluation of the original condition in consideration. The
result returns a Boolean value, i.e., true or false.
• Logical AND, &&, Returns true only if all the operands are true or non-zero
• Logical OR, ||, Returns true if either of the operands is true or non-zero
• Logical NOT, !, Returns true if the operand is false or zero

4. Bitwise Operators
They are works on bit-level. So, compiler first converted to bit-level and then
the calculation is performed on the operands.
• Binary AND, &, Copies a bit to the result if it exists in both operands
• Binary OR, |, Copies a bit to the result if it exists in any of the operands
• Binary XOR, ^, Copies the bit to the result if it is present in either of the
operands but not both
• Left Shift, <<, Shifts the value to the left by the number of bits specified by
the right operand
• Right Shift, >>, Shifts the value to the right by the number of bits specified
by the right operand
• One's Complement, ~, Changes binary digits 1 to 0 and 0 to 1
Note: Only char and int data types can be used with Bitwise Operators.

5. Assignment Operators
They are used to assign value to a variable. We assign the value of right
operand into left operand according to which assignment operator we use.
• Assignment, =, Assigns the value on the right to the variable on the left
• Add and Assignment, +=, Adds the right operand to the left operand and
assigns the result to the left operand
• Subtract and Assignment, -=, Subtracts the right operand from the left
operand and assigns the result to the left operand
• Multiply and Assignment, *=, Multiplies the left operand by the right
operand and assigns the result to the left operand
• Divide and Assignment, /=, Divides the left operand by the right operand
and assigns the result to the left operand

6. Ternary or Conditional Operators


Conditional operator returns the value, based on the condition. This operator
takes three operands, therefore it is known as a Ternary Operator.
Syntax:
Expression1 ? Expression2 : Expression3
In the above statement:
• The ternary operator ? determines the answer on the basis of the evaluation
of Expression1.
• If Expression1 is true, then Expression2 gets evaluated.
• If Expression1 is false, then Expression3 gets evaluated.
• The ternary operator ? determines the answer on the basis of the evaluation
of Expression1.
• If Expression1 is true, then Expression2 gets evaluated.
• If Expression1 is false, then Expression3 gets evaluated.

Expressions

Expressions in C++ are combinations of operators, operands, and function calls that evaluate to a value.
They're fundamental building blocks of C++ programs. Here's a comprehensive overview:
Types of Expressions
Arithmetic Expressions
an arithmetic expression combines variables, literals (constant values), and arithmetic operators to
perform mathematical calculations and produce a numerical result.

int a = 5, b = 3;
int sum = a + b; // Addition
int diff = a - b; // Subtraction
int product = a * b; // Multiplication
int quotient = a / b; // Division
int remainder = a % b; // Modulus
Relational Expressions
a relational expression is a type of expression that compares two operands and evaluates to a
boolean value, either true (often represented as 1) or false (represented as 0). These
expressions use relational operators to establish a relationship between the operands.
bool result1 = (a > b); // Greater than
bool result2 = (a <= b); // Less than or equal
bool result3 = (a == b); // Equal to
bool result4 = (a != b); // Not equal to
Logical Expressions
a logical expression is an expression that evaluates to a boolean value,
either true or false. These expressions are typically formed using logical operators to combine
or modify other boolean or relational expressions.
bool x = true, y = false;
bool and_result = x && y; // Logical AND
bool or_result = x || y; // Logical OR
bool not_result = !x; // Logical NOT
Assignment Expressions
an assignment expression is a statement that assigns a value to a variable using an assignment
operator. The most common assignment operator is the simple assignment operator =
int x = 10; // Simple assignment
x += 5; // Compound assignment (x = x + 5)
x *= 2; // Multiply and assign
int y = x = 20; // Chained assignment

Type Casting

Type casting in C++ is the process of converting a variable or expression from one
data type to another. This can occur either implicitly (automatically by the compiler)
or explicitly (manually by the programmer).

1. Implicit Type Conversion (Coercion):


Implicit type conversion (also known as coercion) is the conversion of one
type of data to another type automatically by the compiler when needed. It
happens automatically when:
• Operations are performed on values of different data types.
• If you pass an argument to a function that expects a different data type.
• Assigning a value of one data type to a variable of another data type.

int i = 10;
happens automatically when:
• Operations are performed on values of different data types.
• If you pass an argument to a function that expects a different data type.
• Assigning a value of one data type to a variable of another data type.

int i = 10;
float f = i; // Implicit conversion from int to float

Explicit Type Conversion


Explicit type conversion, also called type casting is the conversion of one
type of data to another type manually by a programmer. Here the user can
typecast the result to make it of a particular data type. In C++, it can be done
by two ways:

1. C Style Typecasting

This method is inherited by C++ from C. The conversion is done by explicitly


defining the required type in front of the expression in parenthesis. This can
be also known as forceful casting.
(type) expression;
where type indicates the data type to which the final result is converted.

2. C++ Style Typecasting

C++ introduced its own typecasting method using cast operators. Cast
operator is an unary operator which forces one data type to be converted
into another data type. C++ supports four types of casting:
1. Static_Cast: Used for standard compile time type conversions.
2. Dynamic_Cast: Used for runtime type conversion in polymorphism and
inheritance.
3. Const_Cast: Removes or adds const or volatile qualifiers.
4. Reinterpreted_Cast: Used for low-level reinterpretation of bits (e.g.,
converting pointers).

Input-Output Statements

In C++, input and output operations are primarily handled using streams, which are
sequences of bytes flowing into or out of a program. The standard library provides
the iostream header file, which defines the necessary classes and objects for these
operations.

Standard Output (cout)


The cout object is used to display output to the console. It is typically used with the
insertion operator (<<).

#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl; // Prints a string and a newline
int number = 10;
std::cout << "The value of number is: " << number << std::endl; // Prints a variable's value
return 0;
}
#include <iostream>

int main() {
std::cout << "Hello, World!" << std::endl; // Prints a string and a newline
int number = 10;
std::cout << "The value of number is: " << number << std::endl; // Prints a variable's value
return 0;
}

• std::cout: The standard output stream object.


• <<: The insertion operator, used to send data to the output stream.
• std::endl: Inserts a newline character and flushes the output buffer.

Standard Input (cin)


The cin object is used to read input from the console. It is typically used with the
extraction operator (>>).
#include <iostream>
#include <string> // Required for std::string

int main() {
std::string name;
int age;

std::cout << "Enter your name: ";


std::cin >> name; // Reads a string from input

std::cout << "Enter your age: ";


std::cin >> age; // Reads an integer from input

std::cout << "Hello, " << name << "! You are " << age << " years old." << std::endl;
return 0;
}
• std::cin: The standard input stream object.
• >>: The extraction operator, used to retrieve data from the input stream and store it in a
variable.

Storage Classes

C++ Storage Classes are used to describe the characteristics of a


variable/function.
• Determines the lifetime, visibility, default value, and storage location which
helps us to trace the existence of a particular variable during the runtime of a
program.
• Storage class specifiers are used to specify the storage class for a variable.

There are five primary storage classes in C++:

1. auto Storage Class


The auto storage class is the default class of all the variables declared inside a block.
The auto stands for automatic and all the local variables that are declared in a block
automatically belong to this class.
• Scope: Local
• Default Value: Garbage Value
• Memory Location: RAM
• Lifetime: Till the end of its scope

2. extern Storage Class


The extern storage class simply tells us that the variable is defined
elsewhere and not within the same scope (or even source file) where it is
• Memory Location: RAM
• Lifetime: Till the end of its scope

2. extern Storage Class


The extern storage class simply tells us that the variable is defined
elsewhere and not within the same scope (or even source file) where it is
used (i.e. external linkage). Basically, the variable is created in a different
scope or file and can be used in a different file as well.
A normal global variable can be made extern as well by placing the extern
keyword before its declaration/definition in any function/block. The main
purpose of using extern variables is that they can be accessed between two
different files which are part of a large program.
Properties of extern Storage Class Objects
• Scope: Global
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program.

3. static Storage Class


The static storage class is used to declare static variables that have the
property of preserving their value even after they are out of their scope. They
are initialized only once and exist until the termination of the program. Thus,
no new memory is allocated because they are not re-declared. Global static
variables can be accessed anywhere in the program but unlike extern
variable, they have internal linkage so they cannot be accessed outside the
program.
They are declared using static keyword.
Properties of static Storage Class
• Scope: Local
• Default Value: Zero
• Memory Location: RAM
• Lifetime: Till the end of the program

4. register Storage Class


The register storage class declares register variables using the register
keyword which has the same functionality as that of the auto variables. The
only difference is that the compiler tries to store these variables in the
register of the microprocessor if a free register is available. This makes the
use of register variables to be much faster than that of the variables stored in
the memory during the runtime of the program. If a free register is not
available, these are then stored in the RAM.
An important and interesting point to be noted here is that we cannot obtain
the address of a register variable using pointers.
• Scope: Local
• Default Value: Garbage Value
• Memory Location: Register in CPU or RAM
• Lifetime: Till the end of its scope

5. mutable Storage Class


Sometimes there is a requirement to modify one or more data members of
• Default Value: Garbage Value
• Memory Location: Register in CPU or RAM
• Lifetime: Till the end of its scope

5. mutable Storage Class


Sometimes there is a requirement to modify one or more data members of
class/struct through the const function even though you don’t want the
function to update other members of class/struct. This task can be easily
performed by using the mutable keyword. The keyword mutable is mainly
used to allow a particular data member of a const object to be modified.
When we declare a function as const, this pointer passed to the function
becomes const. Adding a mutable to a variable allows a const pointer to
change members.

You might also like