Module_2_Tokens and Function in C++_Lecture Notes
Module_2_Tokens and Function in C++_Lecture Notes
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;
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.
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
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);
}
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.
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;
}
Output:
Enter the values of a and b
10 15
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.
Output
The cube of 3 is: 27
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.
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.
#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);
}
Output
1000
157.26
112500
#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”;
//Function Definition
int add( int a, int b)
{
return (a+b);
}
#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
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
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
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
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
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
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.
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.
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().
void fun(int x)
{
x = 30;
}
int main()
{
int x = 20;
fun(x);
cout << "x = " << x;
return 0;
}
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
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.