C++ Tokens: Keywords, Identifiers, Constants
C++ Tokens: Keywords, Identifiers, Constants
C++ TOKENS
Tokens in C++ are the smallest units of a program that have meaning to the compiler.
They include identifiers, keywords, constants, strings, operators, and punctuation symbols.
The C++ compiler uses tokens to understand and process the source code during
compilation, parsing it into meaningful components for further analysis and execution.
There are 6 types of tokens in C++ :
1. Keyword
2. Identifiers
3. Constants
4. Strings
5. Special symbols
6. Operators
1. Keywords
Keywords in programming languages, including C and C++, are reserved words with
predefined meanings and cannot be used as identifiers (variable names, function names,
etc.).
These keywords are essential to the language syntax and define control structures, data
types, and other language constructs.
int main() {
int x, y, sum;
// prints sum
cout << x << " + " << y << " = " << sum;
return 0;
}
Output:
Enter the two integers you want to add: 3
2
3+2=9
Keywords are predefined reserved words that have a special meaning to the
compiler. These cannot be used as identifiers.
Some of the reserved keywords in C/C++ are given below.
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 class friend new delete
this public private protected inline try
throw catch template
2. Identifiers
Identifiers are symbols or words that one supplies to the variables, functions, types, classes,
objects and other such components of one’s code.
If we look again at the program to add two numbers in C++, we observe that to identify the
value of the first number, we use the identifier ‘x’, for the second number, ‘y’ and for the
sum of the two, we use ‘sum’.
There are some rules that must be followed while using identifiers as tokens in C/C++ these
are as follows:
Keywords cannot be used as identifiers. However, identifiers that contain a keyword are
legal. For example, ‘Tint’ is a legal identifier, but ‘int’ is not.
Identifiers are case-sensitive. Thus ‘FileName’ will correspond to a different memory
address than ‘fileName’.
The first character of an identifier must be an alphabetic character, either uppercase or
lowercase, or an underscore ( _ ). Therefore, ‘2numbers’ is an illegal identifier.
3. Constant
A constant is a token in C that corresponds to a number, character, or character string that
can be used as a value in a program.
Every constant has a type and a value on the basis of which, constants are categorized into
the following types:
Floating Point Constants: It is a decimal number that represents a signed real number. The
representation of a signed real number includes an integer portion, a fractional portion, and an
exponent.
Integer Constants: It is a decimal (base 10), octal (base 8), or hexadecimal (base 16) number
that represents an integral value. We use these to represent integer values that cannot be
changed.
Character Constants: A “character constant” is formed by enclosing a single character from
the representable character set within single quotation marks (‘ ‘).
//floating point constants
15.75 1.575E1 // = 15.75
1575e-2 // = 15.75
2.5e-3 // = -0.0025
25E-4 // = 0.0025
//integer constants
28 0x1C // = Hexadecimal representation for decimal 28
034 // = Octal representation for decimal 28
//character constants
char schar = 'x'; // A character constant
wchar_t wchar = L 'x'; // A wide-character constant for the same character
4. Strings
In the C and C++ programming languages, a string token represents a series of characters
enclosed within double quotes (" ").
It is a basic data type used to represent textual information. String tokens receive their
interpretation as character arrays, and their conclusion involves appending a null character ('\
0') to signify the string's ending.
It enables the handling, storage, and manipulation of textual data within a program.
//Initialize a character array with individual characters
char string1[50] = { 'c', 'o', 'd', 'i', 'n', 'g', 'n', 'i', 'n', 'j', 'a', 's' };
DATA TYPES:
A data type is used to indicate the type of data value stored in a variable. All C compilers
support a variety of data types.
This variety of data types allows the programmer to select the type appropriate to the
needs of the application as well as the machine. ANSI C supports the following classes of
data types:
All the variables in C++ use various data types to restrict the type of data to be stored
during declaration.
If a variable is defined in C++ language, then the compiler allocates some specific
memory based on that particular data type.
Types
There are 3 different Data types in C++, which are:
The data types defined by the user are known as the user-defined data types.
C++ VARIABLES
Variables in C++ is a name given to a memory location. It is the basic unit of storage in
a program.
The value stored in a variable can be changed during program execution.
A variable is only a name given to a memory location, all the operations done on the
variable effects that memory location.
In C++, all the variables must be declared before use.
How to Declare Variables?
A typical variable declaration is of the form:
// Declaring a single variable
type variable_name;
Syntax:
datatype var = value;
datatype: Type of data that can be stored in this variable.
variable_name: Name given to the variable.
value: It is the initial value stored in the variable.
Examples:
// Declaring float variable
float simpleInterest;
Relational Operators
Relational operators are used to compare two values or expressions. These operators return a
boolean value − true if the comparison is correct, and else false.
They are essential for making decisions and controlling the flow of a program based on
conditions.
There are following relational operators supported by C++ language
Assume variable A holds 10 and variable B holds 20, then −
Operato
Description Example
r
Checks if the values of two operands are equal or not, if yes then (A == B) is
==
condition becomes true. not true.
Checks if the values of two operands are equal or not, if values are not (A != B) is
!=
equal then condition becomes true. true.
Checks if the value of left operand is greater than the value of right (A > B) is not
>
operand, if yes then condition becomes true. true.
Checks if the value of left operand is less than the value of right (A < B) is
<
operand, if yes then condition becomes true. true.
Checks if the value of left operand is greater than or equal to the value (A >= B) is
>=
of right operand, if yes then condition becomes true. not true.
Checks if the value of left operand is less than or equal to the value of (A <= B) is
<=
right operand, if yes then condition becomes true. true.
Logical Operators
Logical operators are used to perform logical operations on boolean values (true or false).
These operators are essential for controlling the flow of a program based on conditions.
There are three primary logical operators in C++ as mentioned below −
Operato
Description Example
r
Called Logical AND operator. If both the operands are non-zero, then (A && B) is
&&
condition becomes true. false.
Called Logical OR Operator. If any of the two operands is non-zero, (A || B) is
||
then condition becomes true. true.
Called Logical NOT Operator. Use to reverses the logical state of its
!(A && B)
! operand. If a condition is true, then Logical NOT operator will make
is true.
false.
Bitwise Operators
Bitwise operators are used to perform operations at the bit level on integer data types. These
operations work on direct manipulation of bits, such as low-level programming, graphics,
and cryptography.
Bitwise operator works on bits and perform bit-by-bit operation. The truth tables for &, |,
and ^ are as follows −
0 0 0 0 0
0 1 0 1 1
1 1 1 1 0
1 0 0 1 1
The Bitwise operators supported by C++ language are listed in the following table. Assume variable
A holds 60 and variable B holds 13, then −
Assignment Operators
Assignment operators are used to assign values to variables. These operators allow you to
set or update the value stored in a variable.
Simple assignment operator, Assigns values from right side C = A + B will assign
=
operands to left side operand. value of A + B into C
C <<= 2 is same as C = C
<<= Left shift AND assignment operator.
<< 2
C >>= 2 is same as C = C
>>= Right shift AND assignment operator.
>> 2
C ^= 2 is same as C = C ^
^= Bitwise exclusive OR and assignment operator.
2
Operator precedence determines the grouping of terms in an expression. This affects how an
expression is evaluated. Certain operators have higher precedence than others; for example,
the multiplication operator has higher precedence than the addition operator −
For example x = 7 + 3 * 2; here, x is assigned 13, not 20 because operator * has higher
precedence than +, so it first gets multiplied with 3*2 and then adds into 7.
Here, operators with the highest precedence appear at the top of the table, those with the
lowest appear at the bottom. Within an expression, higher precedence operators will be
evaluated first.
Flowchart of if in C++
Example of if in C++
The below example demonstrates the use of the if statement by finding if the age of a person is
greater than 18 or not. if the condition is true then he/she is allowed to vote.
2. if-else in C++
The if-else decision-making statement allows us to make a decision based on the evaluation
of a given condition. If the given condition evaluates to true then the code inside the 'if'
block is executed and in case the condition is false, the code inside the 'else' block is
executed.
Syntax of if-else in C++
if (condition) {
// Code to be executed if the condition is true
}
else {
// Code to be executed if the condition is false
}
Flowchart of if-else in C++
Example of if-else in C
Output
Growing stage
#include <iostream>
using namespace std;
int main()
{
int number = 44;
if (number > 0)
{
if (number % 2 == 0) {
cout << "positive and even number" << endl;
}
else {
cout << "positive and odd number" << endl;
}
}
else if (number == 0) {
cout << "the number is zero" << endl;
}
else {
cout << "the number is negative" << endl;
}
return 0;
}
Output
positive and even number
// C++ program to demonstrate the use of ternary/conditional operator to find the max from two
numbers
#include <iostream>
using namespace std;
int main()
{
int num1 = 10, num2 = 40;
int max;
max = (num1 > num2) ? num1 : num2;
cout << max;
return 0;
}
Output
40
Output
0
1
2
B) continue
The continue statement is used to skip the loop body for the current iteration and
continue from the next iteration.
Unlike the break statement which terminates the loop completely, continue allows us just
to skip one iteration and continue with the next iteration.
Syntax
continue;
// C++ program to use continue statement to continue the loop when i become 3
#include <iostream>
using namespace std;
int main()
{
for (int i = 0; i < 5; i++) {
if (i == 3) {
continue;
}
cout << i << endl;
}
return 0;
}
Output
0
1
2
4
C) goto
It is a jump statement that is used to transfer the control to another part of the program. It transfers
the control unconditionally to the labeled statement.
Syntax
goto label;
// ...
label:
// Statement or block of code
D) return
The return statement is used to exit the function immediately and optionally returns a
value to the calling function.
It returns to the function from where it was called and if it is the 'main' function then it
marks the end of the execution. So basically, return is a mechanism used to communicate
the results back to the calling function.
Syntax
return expression;
Flowchart of return
// C++ program to use return statement to return the sum calculated by a function
#include <iostream>
using namespace std;
int add(int a, int b)
{
int sum = a + b;
return sum; // Return the sum to the calling code
}
int main()
{
int res = add(3, 5);
cout << "The sum is: " << res << endl;
return 0;
}
Output
The sum is: 8
LOOP STATEMENT
In C++ programming, a loop is an instruction that is used to repeatedly execute a code until a
certain condition is reached. They are useful for performing repetitive tasks without having to
write the same code multiple times.
Loops can be classified on the basis of the sequency in which they check the condition relative to
the execution of the associated block of code.
1. Entry Controlled loops: In this type of loop, the test condition is tested before entering the
loop body.
2. Exit Controlled Loops: In this type of loop, the test condition is tested or evaluated at the end
of the loop body. Therefore, the loop body will execute at least once, irrespective of whether
the test condition is true or false.
C++ provides three loops:
Types of Loops
for Loop
while Loop
do while Loop
for Loop
A for loop is a repetition control structure that allows us to write a loop that is executed a specific
number of times. It is an entry-controlled loop that enables us to perform n number of steps
together in one line.
Syntax
for (initialization; condition; updation) {
// body of for loop
}
The various parts of the for loop are:
Initialization: Initialize the loop variable to some initial value.
Test Condition: This specifies the test condition. If the condition evaluates to true, then body
of the loop is executed, and loop variable is updated according to update expression. If
evaluated false, loop is terminated.
Update Expression: After executing the loop body, this expression increments/decrements the
loop variable by some value.
Example
#include <iostream>
int main() {
for (int i = 1; i <= 5; i++) {
cout << i << " ";
}
return 0;
}
Output
12345
Output
12345
while Loop
while loop is used in situations where we do not know the exact number of iterations of the loop
beforehand. It is an entry-controlled loop whose execution is terminated on the basis of the test
conditions.
Syntax
while (condition) {
// Body of the loop
update expression
}
Only the condition is the part of while loop syntax, we have to do
the initialization and updation manually outside and inside the loop respectively.
Example
#include <iostream>
int main()
{
int i = 1;
while (i <= 5)
{
cout << i << " ";
i++;
}
return 0;
}
Output
12345
do while Loop
The do-while loop is also a loop whose execution is terminated on the basis of test conditions.
The main difference between a do-while loop and the while loop is in the do-while loop the
condition is tested at the end of the loop body, i.e. do-while loop is exit controlled whereas the
other two loops are entry-controlled loops. So, in a do-while loop, the loop body will execute at
least once irrespective of the test condition.
Syntax
do {
// Body of the loop
// Update expression
} while (condition);
Like while loop, only the condition is the part of do while loop syntax, we have to do
the initialization and updation manually outside and inside the loop respectively.
Example
#include <iostream>
int main() {
int i = 1;
do {
cout << i << " ";
i++;
}while (i <= 5);
return 0;
}
Output
12345