0% found this document useful (0 votes)
12 views

Module_2_Tokens and Function in C++_Lecture Notes

best notes

Uploaded by

Varun S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
12 views

Module_2_Tokens and Function in C++_Lecture Notes

best notes

Uploaded by

Varun S
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 20

MODULE 2: Functions and Tokens

TOKENS
The smallest individual units in a program are known as tokens. C++ has following tokens. A C++
programs are written using this token, white spaces and the syntax of the language.
 Keywords
 Identifiers
 Constants
 Strings
 Operators
Keywords
Keywords are explicitly reserved identifiers. Each keyword has a specific function associated with it.
Example: namespace, public
Identifiers
Identifiers refers to the name of the variables, functions, arrays etc created by the user. Each language
has its own rule for defining identifiers. Ex: int a, b; where a and b are identifiers.
Rules for identifiers
1. First character of an identifier can be alphabet or and underscore, digits are not allowed.
2. Keyword cannot be used as an identifier.
3. A Total of 31 characters are allowed
4. Uppercase and lowercase letters are distinct.
Constants
Constants refers to the fixed value that do not change during the execution of the program.
Syntax: const data_type variable_name = value;
Types
1. Integer constants: These constants store values of the int data type.
Example: Const int a= 9;
2. Floating Constants: These constants store values of the floating point data type.
Example: Const float s=0.9;
3. Character constants – These constants store values of the character data type.
Example: const char answer = ‘y’;
4. String constants – These constants are also of the character data type but differ in the declaration
part.
Example: const char title[] = ‘‘DataFlair’’;
5. Octal constants – The number system which consists of only 8 digits, from 0 to 7 is called the
octal number system.
Example: const int oct = 034;
6. Hexadecimal constants – The number system which consists of 16 digits, from 0 to 9 and
alphabets ‘a’ to ‘f’ is called hexadecimal number system.
Example: const int hex = 0x40;

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Strings
Strings can be referred to as an array of characters as well as an individual data type. It is enclosed within
double quotes. The termination of a string in C++ is represented by the null character, that is, ‘\0’. The
size of a string is the number of individual characters it has.
Example: char name[30] = ‘’Hello!”; // The compiler reserves 30 bytes of memory for the string.
string name = “Hello” // The compiler reserves 32 bytes of memory.
Operators (both C and C++)
1. Arithmetic Operators
2. Assignment operators
3. Relational operators
4. Logical operators
5. Bitwise operators
Arithmetic operators: Used to perform arithmetic operations on variables and data.
Example: +, -, *, /, %, ++, --.
Assignment operators: Used to assign values to variables.
Example: =, +=, -+, /=, %=.
Relational operators: It is used to check relationship between the operands, if relation is TRUE it returns
1 and if the relation is False it returns 0.
Example: == , >, <, <=, >=, !=
Logical operators: It is used for Decision making, if relation is TRUE it returns 1 and if the relation is
False it returns 0.
Example: &&, ||, !
Bitwise operators: It is used to perform operations on individual bits.
Example: &, |, ^, ~, >>, <<
Operators in C++
All the operators in C is also accepted in C++, in addition to those in C there are some operators that
are newly introduced in C++.
1. :: Scope resolution operator
2. ::* Pointer to member declarator
3. ->* Pointer to member operator
4. .* Pointer to member Operator
5. delete Memory release operator
6. new Memory allocation operator
7. endl line feed operator
8. setw field width operator
We can give several meaning to an operator depending upon the type of arguments used. This process
is known as operator overloading.

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Scope Resolution Operator
 Same variable names can be used to have different meaning in different blocks. The scope of the
variable extends from the point of its declaration till the end of the block that contains
declaration. The variable present within a block is local variable, the variable defined outside the
block is global variable.
 To access the global version of the variable scope resolution operator :: is used.
Syntax: ::variablename
Program: To show the use of Scope Resolution Operator
#include<iostream>
using namespace std;
int x=20; // Global x
int main()
{
int x = 10; // Local x
cout << "Value of global x is " << ::x;
cout << "\nValue of local x is " << x;
return 0;
}
OUTPUT: Value of global x is 20
Value of local x is 10

Expressions and their Types

 An expression is a combination Operators, Constants and variables arranged as per the rules of
the language.
 An expression may consist of one or more operands and zero or more operators to produce a
value.
 There are seven types of Expressions
1. Constant Expressions
2. Integral Expressions
3. Float Expressions
4. Pointer Expressions
5. Relational Expressions
6. Logical Expressions
7. Bitwise Expressions
 An expression that uses combination combination of above expression is called as compound
expression.
Constant Expression: Constant Expressions consist of only constant values.
Example: 15, ‘x’
Integral Expression: Integral Expressions are those which produce integer results after
implementing all the automatic and explicit type conversions.
Example: m*n where m and n are integer variables.

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Float Expression: Float Expressions are those which after all type conversions produce floating-
point results.
Example: x+y where x and y are floating-point variables.
Pointer Expression: Pointer Expressions produce address values.
Example: &m
ptr
where m is a variable and ptr is a pointer.
Relational Expression: Relational Expressions produce a result of type bool which takes the value
True or False. Relational expression is also known as Boolean expression.
Example: x<=y
a+b = = c+d
when the arithmetic expression is used on the either side of the relational operator, it is
evaluated first and then the result is compared.
Logical Expression: Logical Expression combines two or more relational expression and produce
a result of type bool.
Example: (a>b) && (a==10)

Bitwise Expression: Bitwise Expression are used to manipulate data at bit level. They are
basically used for testing or shifting bits.
Example: x<<3 // shift 3 bit position to left

Special Assignment Expression


1. Chained Assignment
X = (Y=10);
Or
X = Y = 10;
To initialize variables during declaration we should write it as follows
int X=10, Y=10;
2. Embedded Assignment
X = (Y = 50) + 10;
Here Y = 50 is an assignment expression known as embedded expression. Value 50 is assigned
to Y and then 50+10 is assigned to variable X.
Its equivalent to writing
Y = 50;
X = Y + 10;
3. Compound Assignment
Compound Assignment operator is a combination of the assignment operator with a binary
arithmetic operator.
X + = 10;
Here += is known as compound assignment operator. The general form is
Varaiable1 op = Variable2;

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Function Prototyping

Function Prototype: The prototype describes function interface to the compiler by giving details such as
number and type of arguments and the return type of the function. With function prototyping a template
is always used when declaring and defining a function. When a function is called the compiler uses the
template to ensure that the proper arguments are passed and the return value is treated correctly.

Function Prototype is the declaration statement in the calling program and the syntax is
return-type function-name(argument-list);
The argument list contains the types and names of the arguments that must be passed to the function
Example: int add(int a, int b);
In function declaration the variable names are dummy variable names so they are optional
Example: int add(int, int);
In function definition variable names are mandatory because the arguments must be referenced inside
the function.
Example: int add (int a, int b)
{
return (a+b);
}

Program for function


#include<iostream>
Using namespace std;
int add (int , int);
int main()
{
int a=5, b=6,c; //Actual parameters;
c=add(a,b); //calling a function add
cout<<”The sum is = “<<c;
return 0;
}

int add (int x, int y) // x and y are formal parameters


{
return (x+y);
}

Why Do We Need Functions?

 Functions help us in reducing code redundancy. If functionality is performed at multiple places in


software, then rather than writing the same code, again and again, we create a function and call it
everywhere. This also helps in maintenance as we have to change at one place if we make future

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
changes to the functionality.
 Functions make code modular. Consider a big file having many lines of code. It becomes really
simple to read and use the code if the code is divided into functions.
 Functions provide abstraction. For example, we can use library functions without worrying about
their internal work.

Functions can be invoked in two ways: Call by Value or Call by Reference.


 These two ways are generally differentiated by the type of values passed tothem as parameters.
 The parameters passed to the function are called actual parameters whereasthe parameters received
by the function are called formal parameters.

Call By Reference
Reference variables allows us to pass parameters to the function by reference. When we pass arguments
by reference the formal arguments in the called function becomes aliases to the actual arguments in the
calling function. This means that when the function is working with its own argument it is working on
the original data.

Example for call by reference: Program to swap two numbers.


#include<iostream>
Using namespace std;

void swap( int&, int&); // function protype

int main()
{
int a,b; //a and b are actual parameters
cout<<”Enter the values of a and b\n”;
cin>>a>>b;
cout<<”Before swapping a = “<<a<<”b=”<<b<<”\n”;
swap(a,b);
cout<<”After swapping a = “<<a<<”b=”<<b<<”\n”;
return 0;
}

void swap(int &p, int &q)


{
p=p+q;
q=p-q;
p=p-q;
}

Output:
Enter the values of a and b
10 15

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Before swapping a=10 b=15
After swapping a=15 b=10

Return by Reference
A function can also return a reference. Consider the code
int &max(int &a, int &b)
{
if(a>b)
return a;
else
return b;
}
Since the return-type of max is int &, the function returns references to a and b (not values). Then the
function call such as max(c,d) will yield a reference to either c or d depending on its value.
A statement max(c,d)= -1 assigns a value -1 to a if its larger otherwise assigns -1 to b.

Inline Functions
An inline function is a function that is expanded inline when it is invoked. The compiler replaces the
function call with corresponding function code.
Syntax for defining inline function:
inline function-header inline int cube (int a)
{ or {
//function body return (a*a*a);
} }
Inline function is defined by making use of keyword inline and it must be defined before it is called.

Example program for inline function:


#include<iostream>
Using namespace std;
inline float mul (float x, float y)
{
return (x*y);
}
inline float div (float x, float y)
{
return (x/y);
}
int main()
{
int a=2.5, b=1.2;
cout<<mul(a,b)<<”\n”;
cout<<div(a,b)<<”\n”;
return 0;
}

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Output:
3
2.083

Inline Function Program 2


#include <iostream>
using namespace std;
inline int cube(int s)
{
return s * s * s;
}
int main()
{
cout << "The cube of 3 is: " << cube(3) << "\n";return 0;
}

Output
The cube of 3 is: 27

Advantages of Inline function:


1. Inline expansion makes the program run faster because the overhead of a function call and return
is eliminated.
2. Eliminates the cost of calls to small functions.
Disadvantages/Failure of Inline function:
1. For functions returning values if a loop, a switch or goto exists.
2. If a function contain static variable.
3. If inline functions are recursive.
4. Consumes additional memory registers.

Default Arguments
C++ allows a user to call a function without specifying all of its arguments. If argument is not specified
the function assigns a default value to the parameter which does not have a matching argument in the
function call. Default values are specified when the function is declared.
The compiler will look into the prototype to see how many arguments a function uses and alerts the
program for possible default values.

Example: float amount (float principal, int period, float rate=0.15);


In the above example default value of rate is 0.15.

If a function call is written like this


value = amount (5000,7); // one argument is missing
It passes the value of 5000 to principal and 7 to period because the third parameter value is missing
function uses default value of 0.15 for rate.

Reshma, Dept of CSE


MODULE 2: Functions and Tokens

If a function a call is written like this


value = amount(5000,3,0.12) //no argument missing
function passes an explicit value 0.12 to rate.

Advantages of Default Arguments


 We can use default arguments to add new parameters to the existing functions.
 Default arguments can be used to combine similar functions into one.

Function Overloading
Using same function name to create functions that perform a variety of different tasks (operations) is
called Function Overloading.
Using the concept of function overloading we can design a group of functions with one function name
but with different argument list. The function would perform different operations depending on the
argument list in the function call. The correct function to be invoked is determined by checking the
number and type of the arguments but not on the function type. For example an overloaded function
add() function handles different types of data as shown below.
//Declaration
int add (int a, int b); //Prototype 1
int add (int a, int b, int c); //Prototype 2
double add (double x, double y); //Prototype 3

//Function Calls
cout<<add(5,10); //Uses Prototype 1
cout<<add(5,10,15); //Uses Prototype 2
cout<<add(5.35,6.79); //Uses Prototype 3

A function call first matches the prototype having the same number and ty of arguments and then calls
the appropriate function for execution. The function to be selected and executed depends on the
following.
1. The compiler first tries to find an exact match in which the types of actual arguments are the
same, and use that function.
2. If an exact match is not found the compiler uses integral promotions to actual arguments to find
a match.
3. If the first two fails, the compiler tries to use the built-in conversions to the actual arguments and
then uses the function whose match is unique.
4. If all of the above steps fail then the compiler will try the user-defined conversions in
combination with integral promotion and built-in conversions to find a unique match.

Function Overloading Program: To calculate volume of cube, cylinder and rectangle

#include<iostream>
#include<stdlib.h>
Using namespace std;
Reshma, Dept of CSE
MODULE 2: Functions and Tokens
int volume(int);
double volume(double, int);
long volume (long, int, int);

int main()
{
cout<<volume(10)<<”\n”;
cout<<volume(2.5,8)<<”\n”;
cout<<volume(100L, 75,15)<<”\n”;
return 0;
}

//Function Definitions
int volume (int s)
{
Return (s*s*s);
}

double volume ( double r, int h)


{
return (3.14519*r*r*h);
}

long volume (long l, int b, int h)


{
return (l*b*h);
}

Output
1000
157.26
112500

Function Overloading Program: To perform addition on different data types of arguments.

#include<iostream>
#include<stdlib.h>
Using namespace std;
int add(int a, int b); //Function prototype 1
double add(double a, double b); //Function Prototype 2

int main()
{
cout<<add(10,20)<<”\n”;

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
cout<<add(2.5,8.5)<<”\n”;
return 0;
}

//Function Definition
int add( int a, int b)
{
return (a+b);
}

double add( double a, double b)


{
return (a+b);
}
Output:
30
11
Additional Programs and explanation for operators:
Arithmetic Operator
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulo Operation
++ Increment Operator
-- Decrement Operator

#include <iostream>
using namespace std;
int main()
{
int a, b;
a = 7;
b = 2;
// printing the sum of a and b
cout << "a + b = " << (a + b) << endl;
// printing the difference of a and b
cout << "a - b = " << (a - b) << endl;
// printing the product of a and b
cout << "a * b = " << (a * b) << endl;
// printing the division of a by b

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
cout << "a / b = " << (a / b) << endl;
// printing the modulo of a by b
cout << "a % b = " << (a % b) << endl;

cout<<”++a =”<<(++a)<<endl;
cout<<”--b =”<<(--b)<<endl;

return 0;
}
Output:
a+b=9
a–b=5
a * b = 14
a/b=3
a % b =1
++a = 8
--b = 1

Assignment Operators
It is used to assign values to variables.
Operator Example Equivalent to
= a=b; a=b;
+= a+=b a=a+b
-= a-=b a=a-b
/= a/=b a=a/b
*= a*=b a=a*b
#include <iostream>
using namespace std;

int main()
{
int a, b;
// 2 is assigned to a
a = 2;
// 7 is assigned to b
b = 7;
cout << "a = " << a << endl;
cout << "b = " << b << endl;
cout << "\nAfter a += b;" << endl;
// assigning the sum of a and b to a
a += b; // a = a +b
cout << "a = " << a << endl;
return 0;
}
Output

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
a=2
b=7
After a+=b
a=9

Relational Operators
A relational operator is used to check the relationship between two operands. If the relation is TRUE it returns 1
whereas if the relation is FALSE it returns 0

Operator Meaning Example


== Is Equal To 3==5 returns false
!= Not Equal To 3!=5 returns true
> Greater Than 3>5 returns false
< Less Than 3<5 returns true
>= Greater Than or Equal To 3>=5 returns false
<= Less Than or Equal To 3<=5 returns true

Example Program for Relational Operators


#include <iostream>
using namespace std;

int main()
{
int a, b;
a = 3;
b = 5;
bool result;
result = (a == b); // false
cout << "3 == 5 is " << result << endl;
result = (a != b); // true
cout << "3 != 5 is " << result << endl;
result = a > b; // false
cout << "3 > 5 is " << result << endl;
result = a < b; // true
cout << "3 < 5 is " << result << endl;
result = a >= b; // false
cout << "3 >= 5 is " << result << endl;
result = a <= b; // true
cout << "3 <= 5 is " << result << endl;
return 0;
}

Output
3 == 5 is 0
3 != 5 is 1

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
3 > 5 is 0
3 < 5 is 1
3 >= 5 is 0
3 <= 5 is 1

Logical Operators
Logical operators are used to check whether an expression is true or false. If theexpression is true, it
returns 1 whereas if the expression is false, it returns 0. Logical operators are commonly used in decision
making
Operator Example Meaning
&& Expression1&&Expression2 Logical AND, True only if all the operands are true
|| Expression1||Expression2 Logical OR, True only if at least one of the operands is
true
! !Expression Logical NOT, True only if the operands is false

Example Program for Logical Operators


#include <iostream>
using namespace std;
result = (3 != 5) && (3 < 5); // true
cout << "(3 != 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 < 5); // false
cout << "(3 == 5) && (3 < 5) is " << result << endl;
result = (3 == 5) && (3 > 5); // false
cout << "(3 == 5) && (3 > 5) is " << result << endl;
result = (3 != 5) || (3 < 5); // true
cout << "(3 != 5) || (3 < 5) is " << result << endl;
result = (3 != 5) || (3 > 5); // true
cout << "(3 != 5) || (3 > 5) is " << result << endl;
result = (3 == 5) || (3 > 5); // false
cout << "(3 == 5) || (3 > 5) is " << result << endl;
result = !(5 == 2); // true
cout << "!(5 == 2) is " << result << endl;
result = !(5 == 5); // false
cout << "!(5 == 5) is " << result << endl;
return 0;
}

Output
(3 != 5) && (3 < 5) is 1
(3 == 5) && (3 < 5) is 0
(3 == 5) && (3 > 5) is 0
(3 != 5) || (3 < 5) is 1
(3 != 5) || (3 > 5) is 1

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
(3 == 5) || (3 > 5) is 0
!(5 == 2) is 1
!(5 == 5) is 0

Binary Operators
In C++, bitwise operators are used to perform operations on individual bits.They can only be used
alongside char and int data types.
Operator Description
& Binary AND
| Binary OR
^ Binary XOR
~ Binary one’s complement
<< Binary Left Shift
>> Binary Right Shift

Types of Functions
1. User Defined Functions: User Defined functions are user/customer-defined blocks of code specially
customized to reduce the complexity of big programs. They are also commonly known as “tailor-
made functions” which are built only to satisfy the condition in which the user is facing issues
meanwhile reducing the complexity of the whole program.
2. Library Function: Library functions are also called “builtin Functions“. These functions are a part
of a compiler package that is already defined and consists of a special functionwith special and
different meanings. Builtin Function gives us an edge as wecan directly use them without defining
them whereas in the user-definedfunction we have to declare and define a function before
using them. For Example: sqrt(), setw(), strcat(), etc.

Parameter Passing to Functions

The parameters passed to function are called actual parameters. For example,in the program below,
5 and 10 are actual parameters. The parameters received by the function are called formal
parameters. Forexample, in the above program x and y are formal parameters.

Reshma, Dept of CSE


MODULE 2: Functions and Tokens

There are two most popular ways to pass parameters:

1. Pass by Value: In this parameter passing method, values of actual parameters are copied to the
function’s formal parameters and the two types of parameters are stored in different memory
locations. So any changes madeinside functions are not reflected in the actual parameters of
the caller.
2. Pass by Reference: Both actual and formal parameters refer to the same locations, so any changes
made inside the function are actually reflected in the actual parameters of the caller.

Pass by value is used where the value of x is not modified using the functionfun().

// C++ Program to demonstrate function definition


#include <iostream>
using namespace std;

void fun(int x)
{
x = 30;
}
int main()
{
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Output
x = 20

Functions can be invoked in two ways: Call by Value or Call by Reference.


These two ways are generally differentiated by the type of values passed tothem as parameters.
The parameters passed to the function are called actual parameters whereasthe parameters received by
the function are called formal parameters.
Call By Value
In call by value method of parameter passing, the values of actual parametersare copied
to the function’s formal parameters.
 There are two copies of parameters stored in different memory locations.
 One is the original copy and the other is the function copy.
 Any changes made inside functions are not reflected in the actualparameters of the caller.
Example of Call by Value

// C++ program to illustrate call by value


#include <iostream>
using namespace std;
// Function Prototype
void swap(int x, int y);
// Main function
int main()
{
int a = 10, b = 20;
// Pass by Values
swap(a, b);

cout << "In the Caller:\n";


cout << "a = " << a << " b = " << b << endl;
return 0;
}

// Swap functions that swaps two values


void swap(int x, int y)
{
int t;
t = x;x=
y;
y = t;
cout<<"In the Function:\n";
cout << "x = " << x << " y = " << y << endl;
}
Output
Inside Function:
x = 20 y = 10

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
In the Caller:
a = 10 b = 20
Thus actual values of a and b remain unchanged even after exchanging thevalues of x and y in the
function.

Call by Reference
In call by reference method of parameter passing, the address of the actualparameters is passed to the
function as the formal parameters.
 Both the actual and formal parameters refer to the same locations
 Any changes made inside the function are actually reflected in the actualparameters of the caller.
Example of Call by Reference
The following C program is an example of call by reference method.
// C program to illustrate Call by Reference
#include <iostream>
using namespace std;
// Function Prototype
void swap(int&, int&);
// Main function
int main()
{
int a = 10, b = 20;
// Pass reference
swapx(a, b);
cout << "In the Caller:\n";
cout << "a = " << a << " b = " << b << endl;
return 0;
}
// Function to swap two variables by references
void swap(int& x, int& y)
{
int t;
t = x;
x = y;
y = t;
cout << "In the Caller:\n";
cout << "x = " << x << " y = " << y << endl;
}
Output
Inside the Function:x = 20 y = 10
Inside the Caller:a = 20 b = 10

Reshma, Dept of CSE


MODULE 2: Functions and Tokens
Difference between Call by value and Call by reference

Call By Value Call By Reference


While calling a function, we passthe values While calling a function, instead of passing the
of variables to it. Suchfunctions are known as values of variables, we pass the address of
“Call By Values”. variables(location of variables) to the function
known as “Call By References.
In this method, the value of each variable in In this method, the address of actual variables
the calling function is copied into in the calling function is copied into the
corresponding dummy variables of the called dummy variables of thecalled function.
function.
With this method, the changes made to the With this method, using addresses we would
dummy variables in the called function have have access to the actual variables and hence
no effect on the values of actual variables inthe we would be ableto manipulate them.
calling function.
In call-by-values, we cannot alter the values In call by reference, we can alter the values
of actual variables through function calls. of variables through function calls.

Values of variables are passed bythe Simple Pointer variables are necessary to define to
technique. store the address values ofvariables.

This method is preferred when wehave to pass This method is preferred when we haveto pass
some small values that should not change. a large amount of data to the function.

Reshma, Dept of CSE


MODULE 2: Functions and Tokens

Reshma, Dept of CSE

You might also like