0% found this document useful (0 votes)
11 views23 pages

PF Lecture 6b

The document covers variable storage classes in programming, explaining the differences between local (automatic) and global variables, as well as static local variables. It also discusses how arrays can be passed to functions in C++, highlighting the ease of passing entire arrays compared to individual elements. Additionally, the document addresses function overloading, detailing how multiple functions can share the same name as long as their parameter lists differ.

Uploaded by

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

PF Lecture 6b

The document covers variable storage classes in programming, explaining the differences between local (automatic) and global variables, as well as static local variables. It also discusses how arrays can be passed to functions in C++, highlighting the ease of passing entire arrays compared to individual elements. Additionally, the document addresses function overloading, detailing how multiple functions can share the same name as long as their parameter lists differ.

Uploaded by

mashnabsafdar
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 23

Programming

Fundamentals
Lecture 06b
Variable Storage Class
• The scope of a variable determines which parts of the program can access it,
and its storage class determines how long it stays in existence.
• Variables defined inside a block of code have block scope. A block is basically
the code between an opening brace and a closing brace. Thus, a function body
is a block.
• Such variables are called local variables or automatic variables (sometimes).
• Variables defines defined outside the functions are called global variables and
have global scope or file scope.
• There are two storage classes: automatic and static.
• Variables with storage class automatic exist during the lifetime of the
function in which they’re defined.
• Variables with storage class static exist for the lifetime of the program.
Automatic Storage Class
• A local variable is not created until the function in which it is defined is called.
• More accurately, variables defined within any block of code are not created
until the block is executed.
• Thus, variables defined within a loop body only exist while the loop is
executing.
• When a function is called , control is transferred to function definition , the
variables are created and memory space is set aside for them.
• After the execution of return statement, control is passed back to the calling
program, the variables are destroyed, and their values are lost.
• The name automatic is used because the variables are automatically created
when a function is called and automatically destroyed when it returns.
Automatic Storage Class
• The time between the creation and destruction of a variable is called its
lifetime (or sometimes its duration).
• The lifetime of a local variable coincides with the time when the function in
which it is defined is executing.
• The idea behind limiting the lifetime of variables is to save memory space.
• If a function is not executing, the variables it uses during execution are
presumably not needed. Removing them frees up memory that can then be
used by other functions.
• When a local variable is created, the compiler does not try to initialize it.
• Thus, it will start off with an arbitrary value, which may be 0 but probably will
be something else.
Global Variables
• If a global variable is initialized, as in
int exvar = 199;
this initialization takes place when the program is first loaded.
• If a global variable is not initialized explicitly by the program—for example, if it
is defined as
int exvar;
then it is initialized automatically to 0 when it is created.
• This is unlike local variables, which are not initialized and probably contain
random or garbage values when they are created.
• Global variables have storage class static, which means they exist for the life of
the program.
Global Variables
• Memory space is set aside for them when the program begins, and continues
to exist until the program ends.
• You don’t need to use the keyword static when declaring global variables; they
are given this storage class automatically.
Static Local Variables
• Another kind of variable: the static local variable.
• There are static global variables, but they are meaningful only in multifile
programs.
• A static local variable has the visibility of an automatic local variable (that is,
inside the function containing it).
• However, its lifetime is the same as that of a global variable, except that it
doesn’t come into existence until the first call to the function containing it.
• Thereafter it remains in existence for the life of the program.
• Static local variables are used when it’s necessary for a function to remember
a value when it is not being executed; that is, between calls to the function.
• In the next example, a function, getavg(), calculates a running average. It
remembers the total of the numbers it has averaged before, and how many
there were.
Example // getavg()
// finds average of old plus new data
#include <iostream>
using namespace std; float getavg(float newdata)
float getavg(float); //declaration {
int main() static float total = 0; //static variables
{ are initialized
float data=1, avg; static int count = 0; // only once per
while( data != 0 )
{ program
cout << “Enter a number: “; count++; //increment count
cin >> data; total += newdata; //add new data to
avg = getavg(data); total
cout << “New average is “ << avg << endl;
} return total / count; //return the new
return 0; average
} }
//-----------------------------------------------------------
---
Variable Storage types
summary
Passing Arrays to functions
• Array elements can be passed to a called function in the same manner as scalar
variables; they’re simply included as subscripted variables when the function
call is made.
findMin(volts[2], volts[6]);
• Passing a complete array of values to a function is, in many respects, easier
than passing each element.
• The called function receives access to the actual array rather than a copy of
values in the array.
• For example, if volts is an array, the function call findMax(volts); makes the
complete volts array available to the findMax() function.
• This function call is different from passing a single variable to a function.
Example
#include <iostream>
using namespace std;
const int MAXELS = 5;
int findMax(int [MAXELS]); // function prototype
int main()
{
int nums[MAXELS] = {2, 18, 1, 27, 16};
cout << "The maximum value is " << findMax(nums) << endl;
return 0;
}

// Find the maximum value


int findMax(int vals[MAXELS])
{
int i, max = vals[0];
for (i = 1; i < MAXELS; i++)
if (max < vals[i]) max = vals[i];
return max;
}
Only one array
is created
Passing Arrays to functions
• The parameter declaration in the findMax() header contains extra information not
required by the function.
• All that findMax() must know is that the parameter vals references an array of
integers.
• Because the array has been created in main() and no additional storage space is
needed in findMax(), the declaration for vals can omit the array size.
• Therefore, the following is an alternative function header:
int findMax(int vals[])

• In C++, arrays are passed by reference only.


• There is no need to use the symbol & when declaring an array as a formal parameter.
• Because only the starting address of vals is passed to findMax(), the number of
elements in the array need not be included in the declaration for vals.
Array’s starting
address is
passed
Example
#include <iostream>
using namespace std;
int findMax(int [], int); // function prototype
int main()
{
const int MAXELS = 5;
int nums[MAXELS] = {2, 18, 1, 27, 16};
cout << "The maximum value is "
<< findMax(nums, MAXELS) << endl;
return 0;
}

// Find the maximum value


int findMax(int vals[], int numels)
{
int i, max = vals[0];
for (i = 1; i < numels; i++)
if (max < vals[i]) max = vals[i];
return max;
}
Passing Arrays to functions
• Passing two-dimensional arrays to a function is identical to passing one-
dimensional arrays.
• The called function receives access to the entire array.
• For example, if val is a two-dimensional array, the function call display(val);
makes the complete val array available to the display() function.
• Consequently, any changes display() makes are made directly to the val array.
• On the receiving side, the called function must be alerted that a two-
dimensional array is being made available.
• C++ does not allow functions to return a value of the type array.
Example void display(int nums[ROWS]
#include <iostream> [COLS])
#include <iomanip> {
int rownum, colnum;
using namespace std;
for (rownum = 0; rownum <
const int ROWS = 3;
ROWS; rownum++)
const int COLS = 4; {
void display(int [ROWS][COLS]); // function for (colnum = 0; colnum < COLS;
prototype colnum++)
int main() cout << setw(4) <<
{ nums[rownum][colnum];
int val[ROWS][COLS] = {8,16,9,52, cout << endl;
3,15,27,6, }
14,25,2,10}; return;
display(val); }
return 0;
}
Base Address of an Array and Array in
Computer Memory
• The base address of an array is the address (that is, the memory location) of
the first array component.
• For example, if list [ ] is a one-dimensional array, then the base address of list is
the address of the component list[0].
int myList[5];
• This statement declares myList to be an array of five components of type int.
The components are myList[0], myList[1], myList[2], myList[3], and myList[4].
• The computer allocates five memory spaces, each large enough to store an int
value, for these components.
• Moreover, the five memory spaces are contiguous.
• The base address of the array myList is the address of the component
myList[0].
Overloaded Functions
• In a C++ program, several functions can have the same name.
• This is called function overloading, or overloading a function name.
• Two functions are said to have different formal parameter lists if both functions have:
• A different number of formal parameters or
• If the number of formal parameters is the same, then the data type of the formal
parameters, in the order you list them, must differ in at least one position.
• For example, consider the following function headings:
void functionOne(int x)
void functionTwo(int x, double y)
void functionThree(double y, int x)
int functionFour(char ch, int x, double y)
int functionFive(char ch, int x, string name)
These functions all have different formal parameter lists
Overloaded Functions
• Now consider the following function headings:
void functionSix(int x, double y, char ch)
void functionSeven(int one, double u, char firstCh)
• The functions functionSix and functionSeven both have three formal parameters,
and the data type of the corresponding parameters is the same.
• Therefore, these functions have the same formal parameter list.
• To overload a function name, any two definitions of the function must have
different formal parameter lists.
• Function overloading: Creating several functions with the same name.
• The signature of a function consists of the function name and its formal
parameter list.
• Two functions have different signatures if they have either different names or
different formal parameter lists.
Overloaded Functions
• Following function headings correctly overload the function functionXYZ:
void functionXYZ()
void functionXYZ(int x, double y)
void functionXYZ(double one, int y)
void functionXYZ(int x, double y, char ch)

• Consider the following function headings to overload the function functionABC:


void functionABC(int x, double y)
int functionABC(int x, double y)

• Both function headings have the same name and same formal parameter list.
Therefore, these function headings to overload the function functionABC are incorrect.
• In this case, the compiler will generate a syntax error.

You might also like