Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
6 views

Lesson Plan - Functions and scope of variables

The document covers the concepts of functions and variable scope in C++, detailing local and global variables, parameter passing methods (by value and by reference), and default parameter values. It provides examples to illustrate these concepts and explains the implications of variable scope and naming conflicts. Additionally, it includes practice questions to reinforce understanding of the material presented.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

Lesson Plan - Functions and scope of variables

The document covers the concepts of functions and variable scope in C++, detailing local and global variables, parameter passing methods (by value and by reference), and default parameter values. It provides examples to illustrate these concepts and explains the implications of variable scope and naming conflicts. Additionally, it includes practice questions to reinforce understanding of the material presented.
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

Lesson:

Functions and scope of


variables
Pre-Requisites
Syntax of C++
Variables
Loops
Basics of Functions

List of Concepts Involved


Concept of scope of variables in C++
Function call by value
Function call by reference
Default parameter value

Topic: Concept of scope of Variables


The scope of a variable is the part of a program where the variable is valid and can be legally accessed. Legal
? Yes, you read it right. The concept of scope is that precise.

Variables can be classified in the following categories based on their scopes.


Local variables : variables that are declared inside a function block and can be accessed/used inside that
specific function block only. They are unknown entities outside the function.
Global variables : variables that are declared outside all blocks or functions in a program (generally at the
top of the program) and can be accessed/used anywhere in the program (i.e. their reach is not limited to a
block or function)

Note : No two(or more) variables can be declared with the same name within the same scope. However, it is
possible for two(or more) variables to have the same name if they are (all) declared in different scopes.

Cracking the Coding Interview in C++ - Foundation


Lets us understand the concept of scope with the help of different examples:

Example 1 :

#include <iostream>

using namespace std;

void func(){

int a=5; // a is local variable for function func

cout<<a;

int main(){

// cout<<a; // line 1

Here, ‘a’ is a local variable for function func but ‘a’ has no identity outside the function func.

Uncommenting line 1 would produce an error at the time of compilation, because we are trying to access
variable ‘a’ whose scope is limited to the function func().

Example 2 :

#include <iostream>

using namespace std;

//global variable

int p=20;

void func(){

cout<<p;

int main(){

cout<<p; // line 1

Here, p is a global variable and therefore, is accessible from anywhere in the program, Hence, the code will
compile without any error.

Example 3:

#include <iostream>

using namespace std;

int main()

int p = 50;

double p = 60.70;

cout<<(p)<<endl;

Here, as you might have already observed, there are two variables with the same name p that are declared in
the same scope of main () function.

Hence, the code will not compile and throw an error.

Cracking the Coding Interview in C++ - Foundation


Example 4 :

#include<iostream>

using namespace std;

int main()

int p = 5;

int p = 7, q = 9;

cout << p << endl; //7

cout<< q << endl; //9

cout << p << endl; //5

cout<< q << endl;

//error because variable q is not accessible here , it is //out of scope here

Here, p has been declared both as a local and a global variable. Inside the block, the value of p is 7 (as per
local declaration); however, outside the block, the value of p is fetched from the global declaration and the
value of p is 5.

As for q, inside the block, the value of q is 9 (as per local declaration). However, outside the block, q is an
unknown entity, hence the print statement for q, outside the block will simply throw an error.

Common Doubt :

What if there exists a local variable with the same name as that of the global variable inside a function?

If we declare a global variable and a local variable with the same name, then precedence will be given to the
local variable by the compiler i.e. in a region where both local and global variables of the same name exist, all
the operation done on the variable will be done on the local variable only.

If we deliberately want to access the global variable, we may do so using a scope resolution operator. Look at
the example below to have a clear understanding of using a scope resolution operator.

#include <iostream>

using namespace std;

//global variable

int p=23;

int main()

//local variable

int p=32;

p++;

cout<<"value of local variable p is: "<<p<<endl;

cout<<"value of global variable p is: "<<::p;

// scope resolution operator

return 0;

Cracking the Coding Interview in C++ - Foundation


Output:

value of local variable p is: 33

value of global variable p is: 23

This is all about the various possibilities while using scope.

Before proceeding to the next topic of parameter passing (in functions), let us first learn a bit about them.

A parameter is a named variable passed into a function. Yes, we can pass variables in functions too ! This will
help us to use a function to do mathematical calculations, logical operations etc rather than just printing
statements which we were doing till now.

This will also enable us to justifiably utilize the concept of scope.

In C++ functions, there are majorly two types of parameters :

Formal parameters: parameters that are defined during function definition.

Actual parameters: parameters that are passed during the function call in another function.

Confused?! We have got you covered. Let us look at the example below :

// C++ program to show the difference

// between formal and actual parameters

#include <iostream>

using namespace std;

int diff(int p,int q) // p and q are formal parameters

return p-q;

int main ()

int x=89;

int y=9;

cout<<(diff(x,y))<<endl; //x and y are actual parameters

Output: 80

Here, you may also use the same variable name p and q in place of x and y. Note that, in that case, p and q
inside the main function would be different from p and q inside the diff function because both would have
different local scopes limited to the respective functions only.

To perform any operation with the help of functions through parameter passing, we must also be aware that
this can be done in two different ways which brings us to the most interesting topic of functions !

Cracking the Coding Interview in C++ - Foundation


Topic: Parameter passing in a function- Pass by
Value and Pass by Reference
Pass by Value and Pass by reference are the two ways by which we can pass a value or reference to a function
to perform some operation. Let us read more.

Pass by Value: here, the function parameter values (i.e. value from actual parameter) are copied to another
variable (formal parameter).

This is also known as ‘call by value’.

Pass by Reference: here, actual copy of variable reference is passed to the function. This is also known as
‘call by reference’.

Example:

1. Pass by value

void changeValue(int z) {

z = 100; // changeValue has a copy of z, so it doesn't

// overwrite the value of variable a used

// in main() that called changeValue

int main() {

int a = 40;

cout<<a; // prints "40"

changeValue(a);

cout<<a; // prints "40"

Example 2. Pass by value

//Function that calculates the sum

int add (int n1, int n2) //formal parameters

int ans = n1 + n2;

return ans;

int main()

int a, b, ans;

cout<<("Enter the first number: ")<< endl;

cin>>a;

cout<<("Enter the second number: ")<< endl;

cin>>b;

ans = add(a, b); //actual parameters

cout<<("The sum of two numbers a and b is: ")<< ans << endl;

Cracking the Coding Interview in C++ - Foundation


In the example above, we are passing two values a and b (entered by the user) in a function ‘add’ as n1 and n2.
The value of sum is saved in variable ans and this value is returned from add function to ‘ans’ variable in
main().

We are now going to discuss parameter passing by reference. It is being discussed separately here because it
is a little different from whatever we have learnt so far.

Topic: Pass by reference:


Parameter passing ‘by reference’ means that we pass the reference to the actual variables rather than passing
just the value (as we did in ‘passing by value’).

To access the address/reference of any variable, we use the "&" operator. Look at the example below to
understand the use of ‘&’ operator and its use in passing by reference.

#include <iostream>

using namespace std;

void swap(int &a, int &b)

int c = a;

a = b;

b = c;

int main()

int num1 = 20;

int num2 = 32;

cout << "Before swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

// Call the function swap, which will change the values of num1

// and num2

swap(num1, num2);

cout << "After swap: " << "\n";

cout << num1 <<" "<< num2 << "\n";

return 0;

Output:

Before swap:

20 32

After swap:

32 20

Cracking the Coding Interview in C++ - Foundation


Here, the reference/address of num1 and num2 are being passed to parameters a and b of the ‘swap’ function.

After the swapping operation in the ‘swap’ function, the values are changed in the reference/address of the
variables which are printed in the main function.

If it appears confusing to you, you are not the only one! Don't worry, we will cover the reference concept more in
the forthcoming lecture on pointers.

The next topic is extremely interesting and equally important. Let us understand it with a little attention.

Topic :Default parameter/argument value


A default argument is a value in the function declaration assigned automatically by the compiler if the calling
function does not pass any value to that argument.

If a function with default arguments is called without passing arguments, then the default parameters are
used. However, if arguments are passed while calling the function, the default arguments are ignored.

Let us look at the example below :

// CPP Program to demonstrate Default Arguments

#include <iostream>

using namespace std;

// A function with default arguments,

// it can be called with

// 2 arguments or 3 arguments or 4 arguments.

int add(int a, int b, int c = 0, int d = 10)

//assigning default values to c,d as 0,10 respectively

return (a + b + c + d);

// Driver Code

int main()

// Statement 1

cout << add(30, 20) << endl;

// Statement 2

cout << add(10, 20, 30) << endl;

// Statement 3

cout << add(5, 20, 35, 50) << endl;

return 0;

Output:

60

70

110

Cracking the Coding Interview in C++ - Foundation


In the example above, we have called the add function three times
add(30,20)

When this function is called, it reaches out to the definition of the ‘add’. There it initializes a to 30, b to 20 and

the c to 0 , d to 10 by default as no value is passed. After addition of all these values gives 60 as output.
Sum(10, 20, 30)

When this function is called, a is assigned as 10, b is assigned as 20, the third parameter c is initialized to 30

instead of zero. The last value d remains 10. The sum of a,b,c,d is 70 which is returned as output.
Sum(5, 20, 35, 50)

In this function call, there are four parameter values passed into the function with a as 5, b as 20, c is 35, and

d as 50. All the values are then summed up to give 110 as the output.

We hope that the concept of default argument is pretty clear with all these combination of scenarios discussed
above.

Note: Once you have used the default value for an argument in the function definition, all subsequent
arguments must have a default value as well. This can also be stated that the default arguments are assigned
from right to left.

For example, the following function definition is invalid as the subsequent argument of the default variable d is
not default.

// Invalid because c has default value, but d after it doesn't have a default value

int sum(int a, int b, int c = 0, int d).

That brings us to the end of the function concept !

Let us now look at the practice questions :

Q1. What is the output of the following code?

void decrease(int n1, int n2)

n1--;

n2 = n2 - 2;

cout<<(n1) << ":" << (n2);

// n1 and n2 are formal parameters

int main()

int p = 26;

int q = 13;

decrease(p,q);

cout<<(p) << ":" << (q);

// p and q are actual parameters.

Ans:

25: 11

26: 13

Cracking the Coding Interview in C++ - Foundation


Explanation:

In this program snippet, changes in the values of n1 and n2 are not reflected to p and q because n1 and n2 are
formal parameters and are local to function decrease so any changes in their values here won’t affect
variables p and q inside main function.

Q2. What will be the output of the following code ?

void makeTwice(int p )

p = p * 2;

int main()

int p = 24;

makeTwice(p);

cout<<(p);

Ans : 24

Explanation:

In the code snippet, changes in the value of p is not reflected in the main function

Here we are calling the function makeTwice using the concept of ‘pass by value’.

Q3. Will the following code generate any error ?

void temp(int p)

int q = p;

q = q -100;

int main()

int p = 890;

temp(p);

cout<<(q)<<endl;

Ans: Yes, it will generate an error, because, in the main function there is no variable having name q,variable q
has scope in temp function block only.

Cracking the Coding Interview in C++ - Foundation


Q4. What is the scope of the variable declared in the user defined function?

a) only inside the {} block

b) whole program

c) header section

d) the main function

Ans: A only inside the {} block

That is all ! See you in the next lesson !! Till then, keep learning ! Keep exploring !!

Upcoming Class Teasers


Arrays

Cracking the Coding Interview in C++ - Foundation

You might also like