KEMBAR78
Module 2 C | PDF | Parameter (Computer Programming) | Scope (Computer Science)
0% found this document useful (0 votes)
4 views25 pages

Module 2 C

This document covers functions in C++, detailing the language's tokens, keywords, identifiers, constants, and data types. It introduces reference variables, operators, scope resolution, expressions, and function prototyping, highlighting improvements made in C++ over C. Additionally, it explains call by reference and the significance of function prototypes in ensuring type safety during function calls.

Uploaded by

mobilemagic9773
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)
4 views25 pages

Module 2 C

This document covers functions in C++, detailing the language's tokens, keywords, identifiers, constants, and data types. It introduces reference variables, operators, scope resolution, expressions, and function prototyping, highlighting improvements made in C++ over C. Additionally, it explains call by reference and the significance of function prototypes in ensuring type safety during function calls.

Uploaded by

mobilemagic9773
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
You are on page 1/ 25

Functions in C++ Module-2

Module-2
Functions in C++

Introduction

As mentioned earlier, C++ is a superset of C and therefore most constructs of C


are legal in C++ with their meaning unchanged. However, there are some exceptions and
additions. In this chapter, we shall discuss these exceptions and additions with respect
to tokens and control structures.

Tokens

As we know, the smallest individual units in a program are known as tokens. C++
has the following tokens:
• Keywords
• Identifiers
• Constants
• Strings
• Operators
A C++ program is written using these tokens, white spaces, and the syntax of the
language. Most of the C++ tokens are basically similar to the C tokens with the exception
of some additions and minor modifications.

Keywords
The keywords implement specific C++ language features. They are explicitly reserved
identifiers and cannot be used as names for the program variables or other user-defined
program elements.
Below Table gives the complete set of C++ keywords. Many of them are common to both
C and C++.
The ANSI C keywords are shown in boldface. Additional keywords have been added to
the ANSI C keywords in order to enhance its features and make it an object-oriented
language. ANSI C++ standards committee has added some more keywords to make the
language more versatile. These are shown separately.

Dept. of CSE,RYMEC,Ballari Page 1


Functions in C++ Module-2

Identifiers and Constants

 Identifiers refer to the names of variables, functions, arrays, classes, etc., created
by the programmer.
 They are the fundamental requirement of any language.
 Each language has its own rules for naming these identifiers.
The following rules are common to both C and C++:
 Only alphabetic characters, digits and underscores are permitted.
 The name cannot start with a digit.
 Uppercase and lowercase letters are distinct.
 A declared keyword cannot be used as a variable name.

 A major difference between C and C++ is the limit on the length of a name.
 While ANSI C recognizes only the first 32 characters in a name, ANSI C++ places
no limit on its length and, therefore, all the characters in a name are significant.
 Care should be exercised while naming a variable which is being shared by more
than one file containing C and C++ programs.

 Constants refer to fixed values that do not change during the execution of a
program.

Dept. of CSE,RYMEC,Ballari Page 2


Functions in C++ Module-2

 Like C, C++ supports several kinds of literal constants. They include integers,
characters, floating point numbers and strings.
 Literal constant do not have memory locations.

Examples:
123 // decimal integer
12.34 // floating point integer
037 // octal integer
0X2 // hexadecimal integer
“C++” // string constant
‘A’ // character constant
L‘ab’ // wide-character constant

 The wchar_t type is a wide-character literal introduced by ANSI C++ and is


intended for character sets that cannot fit a character into a single byte. Wide-
character literals begin with the letter L.
 C++ also recognizes all the backslash character constants available in C.

Basic Data Types

Data types in C++ can be classified under various categories as shown in Fig. 3.1.

Dept. of CSE,RYMEC,Ballari Page 3


Functions in C++ Module-2

Both C and C++ compilers support all the built-in (also known as basic or fundamental)
data types. With the exception of void, the basic data types may have several modifiers
preceding them to serve the needs of various situations. The modifiers signed,
unsigned, long, and short may be applied to character and integer basic data types.
However, the modifier long may also be applied to double. Data type representation is
machine specific in C++.
Below Table lists all combinations of the basic data types and modifiers along with their
size and range for a 16-bit word machine.

Reference Variables

 C++ introduces a new kind of variable known as the reference variable. A


reference variable provides an alias (alternative name) for a previously defined
variable.
 For example, if we make the variable sum a reference to the variable total, then
sum and total can be used interchangeably to represent that variable.
A reference variable is created as follows:

data-type & reference-name = variable-name


Example:
float total = 100;
float & sum = total;

Dept. of CSE,RYMEC,Ballari Page 4


Functions in C++ Module-2

total is a float type variable that has already been declared; sum is the alternative name
declared to represent the variable total. Both the variables refer to the same data object
in the memory.
Now, the statements
cout << total;
and
cout << sum;
both print the value 100. The statement
total = total + 10;
will change the value of both total and sum to 110. Likewise, the assignment
sum = 0;
will change the value of both the variables to zero.

Operators in C++
 C++ has a rich set of operators. All C operators are valid in C++ also.
 In addition, C++ introduces some new operators.
 We have already seen two such operators, namely, the insertion operator <<, and
the extraction operator >>.
Other new operators are;
:: Scope resolution operator
::* Pointer-to-member declarator
->* Pointer-to-member operator
.* Pointer-to-member operator
delete Memory release operator
endl Line feed operator
new Memory allocation operator
setw Field width operator

In addition, C++ also allows us to provide new definitions to some of the built-in
operators. That is, we can give several meanings to an operator, depending upon the
types of arguments used. This process is known as operator overloading.

Dept. of CSE,RYMEC,Ballari Page 5


Functions in C++ Module-2

Scope Resolution Operator

 Like C, C++ is also a block-structured


block structured language. Blocks and scopes can be used in
constructing programs.
 We know that the same variable name can be used to have different meanings in
different blocks.
 The scope of the variable extends from the point of its declaration till the end of
the block containing the declaration.
 A variable declared inside a block is said to be local to that block.
Consider the following segment of a program:
....
....
{
int x=10;
....
....
}
....
....
{
int x=10;
....
....
}

 The two declarations of x refer to two different memory locations containing


different values.
 Statements in the second block cannot refer to the variable x declared in the first
block, and vice versa. Blocks in C++ are often nested.
For example, the following style is common:

Dept. of CSE,RYMEC,Ballari Page 6


Functions in C++ Module-2

 Block2 is contained in block1. Note that a declaration in an inner block hides a


declaration of the same variable in an outer block and, therefore, each
declaration of x causes it to refer to a different data object.
 Within the inner block, the variable x will refer to the data object declared
therein.
 In C, the global version of a variable cannot be accessed from within the inner
block.
 C++ resolves this problem by introducing a new operator :: called the scope
resolution operator. This can be used to uncover a hidden variable.
It takes the following form: :: variable-name

This operator allows access to the global version of a variable.


Example Program;
#include <iostream.h>
#include<conio.h>
int m = 10; // global m
void main()
{
int m = 20; // m redeclared, local to main
{
int k = m;
int m = 30; // m declared again
// local to inner block
cout << “we are in inner block \n”;
cout << “k = ” << k << “\n”;
cout << “m = ” << m << “\n”;
cout << “::m = ” << ::m << “\n”;
}
cout << “\nWe are in outer block \n”;
cout << “m = ” << m << “\n”;
cout << “::m = ” << ::m << “\n”;
getch();
}

Dept. of CSE,RYMEC,Ballari Page 7


Functions in C++ Module-2

Output : We are in inner block


k = 20
m = 30
::m = 10
We are in outer block
m = 20
::m = 10

Expressions and their Types

 An expression is a combination of operators, constants and variables arranged as


per the rules of the language.
 It may also include function calls which return values. An expression may consist
of one or more operands, and zero or more operators to produce a value.
Expressions may be of the following seven types:
 Constant expressions
 Integral expressions
 Float expressions
 Pointer expressions
 Relational expressions
 Logical expressions
 Bitwise expressions
An expression may also use combinations of the above expressions. Such expressions
are known as compound expressions.

 Constant Expressions
Constant expressions consist of only constant values.
Examples:
15
20 + 5 / 2.0
‘x’

Dept. of CSE,RYMEC,Ballari Page 8


Functions in C++ Module-2

 Integral Expressions
Integral expressions are those which produce integer results after implementing all the
automatic and explicit type conversions.
Examples:
m
m*n-5
m * ‘x’
5 + int(2.0)
where m and n are integer variables.
 Float Expressions
Float expressions are those which, after all conversions, produce floating-point results.
Examples:
x+y
x * y / 10
5 + float(10)
10.75
where x and y are floating-point variables.

 Pointer Expressions
Pointer expressions produce address values.
Examples:
&m
ptr
ptr + 1
“xyz”
where m is a variable and ptr is a pointer.

 Relational Expressions
Relational expressions yield results of type bool which takes a value true or false.
Examples:
x <= y
a+b == c+d
m+n > 100

Dept. of CSE,RYMEC,Ballari Page 9


Functions in C++ Module-2

When arithmetic expressions are used on either side of a relational operator, they will
be evaluated first and then the results compared.
Relational expressions are also known as Boolean expressions.

 Logical Expressions
Logical expressions combine two or more relational expressions and produces bool
type results.

Examples:
a>b && x==10
x==10 || y==5

 Bitwise Expressions
Bitwise expressions are used to manipulate data at bit level. They are basically used
for testing or shifting bits.
Examples:
x << 3 // Shift three bit position to left
y >> 1 // Shift one bit position to right
Shift operators are often used for multiplication and division by powers of two.

Special Assignment Expressions


 Chained Assignment
x = (y = 10);
or
x =y = 10;
First 10 is assigned to y and then to x.
A chained statement cannot be used to initialize variables at the time of declaration.
For instance, the statement
float a = b = 12.34; // wrong
is illegal. This may be written as
float a=12.34, b=12.34 // correct

Dept. of CSE,RYMEC,Ballari Page 10


Functions in C++ Module-2

 Embedded Assignment
x = (y = 50) + 10;
(y = 50) is an assignment expression known as embedded assignment. Here, the value
50 is assigned to y and then the result 50+10 = 60 is assigned to x.
This statement is identical to
y = 50;
x = y + 10;

 Compound Assignment
Like C, C++ supports a compound assignment operator which is a combination of the
assignment operator with a binary arithmetic operator.
For example, the simple assignment statement
x = x +10;
may be written as
x +=10;
The operator += is known as compound assignment operator
or short-hand assignment operator.
The general form of the compound assignment operator is
variable1 op= variable2;
where op is a binary arithmetic operator. This means that
variable1 = variable1 op variable2;

Dept. of CSE,RYMEC,Ballari Page 11


Functions in C++ Module-2

Function Prototyping

 Function prototyping is one of the major improvements added to C++


functions.
 The prototype describes the function interface to the compiler by giving
details such as the number and type of arguments and the type of return
values.
 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
proper arguments are passed, and the return value is treated correctly.
 Any violation in matching the arguments or the return types will be caught
by the compiler at the time of compilation itself. These checks and controls
did not exist in the conventional C functions.
Remember, C also uses prototyping. But it was introduced first in C++ by
Stroustrup and the success of this feature inspired the ANSI C committee to
adopt it. However, there is a major difference in prototyping between C and C++.
While C++ makes the prototyping essential, ANSI C makes it optional, perhaps, to
preserve the compatibility with classic C.
Function prototype is a declaration statement in the calling program and is of the
following form:
type function-name (argument-list);

The argument-list contains the types and names of arguments that must be passed to
the function.
Example:
 float volume(int x, float y, float z);
Note that each argument variable must be declared independently inside the
parentheses. That is, a combined declaration like
 float volume(int x, float y, z); is illegal.
In a function declaration, the names of the arguments are dummy variables and
therefore , they are optional. That is, the form
 float volume(int, float, float);

Dept. of CSE,RYMEC,Ballari Page 12


Functions in C++ Module-2

is acceptable at the place of declaration. At this stage, the compiler only checks for the
type of arguments when the function is called.
In general, we can either include or exclude the variable names in the argument list of
prototypes.
The variable names in the prototype just act as placeholders and, therefore, if names are
used, they don’t have to match the names used in the function call or function
definition.

 In the function definition, names are required because the arguments must be
referenced inside the function.
Example:
float volume(int a, float b, float c)
{
float v = a*b*c;
.....
.....
}
The function volume() can be invoked in a program as follows:
float cube1 = volume(b1,w1,h1); // Function call
 The variable b1, w1, and h1 are known as the actual parameters which specify
the dimensions of cube1.
 Their types (which have been declared earlier) should match with the types
declared in the prototype. Remember, the calling statement should not include
type names in the argument list.

We can also declare a function with an empty argument list, as in the following example:
void display( );

In C++, this means that the function does not pass any parameters. It is identical to the
statement
void display(void);

Dept. of CSE,RYMEC,Ballari Page 13


Functions in C++ Module-2

However, in C, an empty parentheses implies any number of arguments. That


is, we have fore- gone prototyping. A C++ function can also have an ‘open’
parameter list by the use of ellipses in the prototype as shown below:

void do_something(...);

Call By Reference

 In traditional C, a function call passes arguments by value. The called function


creates a new set of variables and copies the values of arguments into them.
 The function does not have access to the actual variables in the calling program
and can only work on the copies of values. This mechanism is fine if the function
does not need to alter the values of the original variables in the calling program.
 Provision of the reference variables in C++ permits us to pass parameters to the
functions by reference.
 When we pass arguments by reference, the ‘formal’ arguments in the called
function become aliases to the ‘actual’ arguments in the calling function.
 This means that when the function is working with its own arguments, it is
actually working on the original data.

Consider the following function:


void swap(int &a, int &b) // a and b are reference variables
{
int t = a; // Dynamic initialization
a = b;
b = t;
}

Now, if m and n are two integer variables, then the function call
swap(m, n);
will exchange the values of m and n using their aliases (reference variables)
a and b.
In traditional C, this is accomplished using pointers and indirection as follows:

Dept. of CSE,RYMEC,Ballari Page 14


Functions in C++ Module-2

void swap1(int *a, int *b) /* Function definition */


{
int t;
t = *a; /* assign the value at address a to t */
*a = *b; /* put the value at b into a */
*b = t; /* put the value at t into b */
}
This function can be called as follows:
swap1(&x, &y); /* call by passing */
/* addresses of variables */
This approach is also acceptable in C++. Note that the call-by-reference method is neater
in its approach.

Program:

#include <iostream.h>
#include<conio.h>
// function declaration
void swap(int &x, int &y);
void main ()
{
// local variable declaration:
int a = 100;
int b = 200;
clrscr();
cout << "Before swap, value of a :" << a << endl;
cout << "Before swap, value of b :" << b << endl;
/* calling a function to swap the values using variable reference.*/
swap(a, b);
cout << "\nAfter swap, value of a :" << a << endl;
cout << "After swap, value of b :" << b << endl;
getch();
}

Dept. of CSE,RYMEC,Ballari Page 15


Functions in C++ Module-2

// function definition to swap the values.


void swap(int &x, int &y)
{
int temp;
temp = x; /* save the value at address x */
x = y; /* put y into x */
y = temp; /* put x into y */
}

Output:

Before swap, value of a :100


Before swap, value of b :200

After swap, value of a :200


After swap, value of b :100

Return by Reference
A function can also return a reference. Consider the following function:

int &max(int &x, int &y)


{
if (x > y) return x;
else
return y;
}

Since the return type of max() is int &, the function returns reference to x or y (and not
the values). Then a function call such as max(a, b) will yield a reference to either a or b
depending on their values. This means that this function call can appear on the left-hand
side of an assignment statement.
That is, the statement.
max(a,b) = -1;

is legal and assigns –1 to a if it is larger, otherwise –1 to b

Dept. of CSE,RYMEC,Ballari Page 16


Functions in C++ Module-2

Inline Functions
 One of the objectives of using functions in a program is to save some
memory space, which becomes appreciable when a function is likely to be
called many times.
 However, every time a function is called, it takes a lot of extra time in
executing a series of instructions for tasks such as jumping to the function,
saving registers, pushing arguments into the stack, and returning to the
calling function.
 When a function is small, a substantial percentage of execution time may
be spent in such overheads.
 One solution to this problem is to use macro definitions, popularly known as
macros. Preprocessor macros are popular in C.
 The major drawback with macros is that they are not really functions and
therefore, the usual error checking does not occur during compilation.
 C++ has a different solution to this problem. To eliminate the cost of calls to
small functions, C++ proposes a new feature called inline function.
 An inline function is a function that is expanded in line when it is invoked.
 That is, the compiler replaces the function call with the corresponding
function code .

The inline functions are defined as follows:

inline function-header
{
function body
}

Example:

inline double cube(double a)


{
return(a*a*a);
}

Dept. of CSE,RYMEC,Ballari Page 17


Functions in C++ Module-2

The above inline function can be invoked by statements like


c = cube(3.0);
d = cube(2.5+1.5);
 On the execution of these statements, the values of c and d will be 27 and
64 respectively. If the arguments are expressions such as 2.5 + 1.5, the
function passes the value of the expression, 4 in this case. This makes
the inline feature far superior to macros.
 It is easy to make a function inline. All we need to do is to prefix the
keyword inline to the function definition. All inline functions must be
defined before they are called.
 We should exercise care before making a function inline. The speed
benefits of inline functions diminish as the function grows in size. At some
point the overhead of the function call becomes small compared to the
execution of the function, and the benefits of inline functions may be lost.
 In such cases, the use of normal functions will be more meaningful.
Usually, the functions are made inline when they are small enough to be
defined in one or two lines.

Example:

inline double cube(double a) {return(a*a*a);}


Some of the situations where inline expansion may not work are:
 For functions returning values, if a loop, a switch, or a goto exists.
 For functions not returning values, if a return statement exists.
 If functions contain static variables.
 If inline functions are recursive.

Dept. of CSE,RYMEC,Ballari Page 18


Functions in C++ Module-2

Program:

#include <iostream.h>
#include<conio.h>
inline float mul(float x, float y)
{
return(x*y);
}
inline double div(double p, double q)
{
return(p/q);
}
int main()
{
float a = 12.345;
float b = 9.82;
cout << mul(a,b) << “\n”;
cout << div(a,b) << “\n”;
return 0;
}

Output:
121.228
1.25713

Dept. of CSE,RYMEC,Ballari Page 19


Functions in C++ Module-2

Default Arguments
 C++ allows us to call a function without specifying all its arguments. In such
cases, 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 looks at
the prototype to see how many arguments a function uses and alerts the
program for possible default values.
Here is an example of a prototype (i.e., function declaration) with default values:

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


The default value is specified in a manner syntactically similar to a variable
initialization. The above prototype declares a default value of 0.15 to the
argument rate. A subsequent function call like

value = amount(5000,7); // one argument missing


passes the value of 5000 to principal and 7 to period and then lets the function
use default value of
0.15 for rate. The call
value = amount(5000,5,0.12); // no missing argument
passes an explicit value of 0.12 to rate.
 A default argument is checked for type at the time of declaration and evaluated
at the time of call.
 One important point to note is that only the trailing arguments can have default
values and therefore we must add defaults from right to left.
 We cannot provide a default value to a particular argument in the middle of an
argument list.
Some examples of function declaration with default values are:
int mul(int i, int j=5, int k=10); // legal
int mul(int i=5, int j); // illegal
int mul(int i=0, int j, int k=10); // illegal
int mul(int i=2, int j=5, int k=10); // legal
 Default arguments are useful in situations where some arguments always
have the same value.

Dept. of CSE,RYMEC,Ballari Page 20


Functions in C++ Module-2

#include<iostream.h>
Program:
#include<conio.h>
void main()
{
float amount;
float value(float p, int n, float r=0.15); //prototype
void printline(char ch='*',int len=10); //prototype
printline(); //use default values for arguments
amount = value (5000.00,5); //default for 3rd argument
cout<<“\n Final Value = ”<<amount<<“\n\n”;
amount = value (10000.00,5,0.30); //pass all arguments explicitly
cout<<“\n Final Value = ”<<amount<<“\n\n”;
printline(‘=’); //use default value for second argument
getch();
}
float value (float p, int n, float r)
{
int year = 1;
float sum = p;
while(year<=n)
{
sum = sum*(1+r);
year = year+1;
}
return(sum);
}
void printline(char ch, int len)
{
for(int i=1;i<=len;i++)
cout<<ch<<”\t”;
}

**********
Output: Final Value = 10056.8
Final Value = 37129.3
==========

Dept. of CSE,RYMEC,Ballari Page 21


Functions in C++ Module-2

Function Overloading
 As stated earlier, overloading refers to the use of the same thing for
different purposes. C++ also permits overloading of functions.
 This means that we can use the same function name to create
functions that perform a variety of different tasks. This is known as
function polymorphism in OOP.
 Using the concept of function overloading; we can design a family of
functions with one function name but with different argument lists.
 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 add() function handles different types of data as
shown as follows:

// Declarations
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
double add(int p, double q); // prototype 4
double add(double p, int q); // prototype 5
// Function calls
cout << add(5, 10); // uses prototype 1
cout << add(15, 10.0); // uses prototype 4
cout << add(12.5, 7.5); // uses prototype 3
cout << add(5, 10, 15); // uses prototype 2
cout << add(0.75, 5); // uses prototype 5

 A function call first matches the prototype having the same number and
type of arguments and then calls the appropriate function for execution. A
best match must be unique.

Dept. of CSE,RYMEC,Ballari Page 22


Functions in C++ Module-2

The function selection involves the following steps:


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 the integral promotions to
the actual arguments, such as,
char to int
float to double

to find a match.

3. When either of them fails, the compiler tries to use the built-in
conversions (the implicit assignment conversions) to the actual
arguments and then uses the function whose match is unique. If the
conversion is possible to have multiple matches, then the compiler will
generate an error message. Suppose we use the following two functions:
long square(long n)
double square(double x)

A function call such as

square(10)

will cause an error because int argument can be converted to either long
or double, thereby creating an ambiguous situation as to which version of
square() should be used.
4. If all of the steps fail, then the compiler will try the user-defined conversions
in combination with integral promotions and built-in conversions to find a
unique match. User-defined conversions are often used in handling class
objects.

Dept. of CSE,RYMEC,Ballari Page 23


Functions in C++ Module-2

Program illustrates function overloading:


//Function area() is overloaded three times
#include<iostream.h>
#include<conio.h>
//Declaration of Function Prototypes
int area (int);
int area (int, int);
float area (float);
void main()
{
cout<<"Calling the area() function for computing the area of a square (side = 5) : "
<<area(5)<<"\n";
cout<<"Calling the area() function for computing the area of a rectangle (length = 5,
breadth = 10) : "<<area(5,10)<<"\n";
cout<<"Calling the area() function for computing the area of a circle (radius = 5.5):”
<<area(5.5);
getch();
}
int area (int side) //Area of square
{
return(side*side);
}
int area (int length, int breadth) //Area of rectangle
{
return(length*breadth);
}
float area (float radius) //Area of circle
{
return(3.14*radius*radius);
}

Dept. of CSE,RYMEC,Ballari Page 24


Functions in C++ Module-2

Output:

Calling the area() function for computing the area of a square (side = 5) : 25

Calling the area() function for computing the area of a rectangle (length = 5, breadth = 10) : 50

Calling the area() function for computing the area of a circle (radius = 5.5) : 94.99

Dept. of CSE,RYMEC,Ballari Page 25

You might also like