cpp07 - scope

21
Scope Michael Heron

Upload: michael-heron

Post on 29-Nov-2014

69 views

Category:

Software


0 download

DESCRIPTION

This is an introductory lecture on C++, suitable for first year computing students or those doing a conversion masters degree at postgraduate level.

TRANSCRIPT

Page 1: CPP07 - Scope

ScopeMichael Heron

Page 2: CPP07 - Scope

Introduction• Having discussed the idea of functions, we can now move on

to one of the consequences.• The idea of variable scope.

• Scope is what defines the lifetime of a variable.• Variables have a life-cycle which they follow.• Scope determines their life-span.

• This has particular importance for functions and when we talk about pointers in the next lecture.

Page 3: CPP07 - Scope

Scope#include <iostream>

using namespace std;

int add_nums (int x, int y) { int answer; answer = x + y; return answer;}

int main() { add_nums (10, 20); cout << answer << endl; return 1;}

Page 4: CPP07 - Scope

Scope• This program will not compile.• It will complain about variables not being defined as being in

scope.• Variables that are defined within a function are accessible only

within that function.• They cannot be accessed in other functions.

• Variables defined in functions are known as local variables.• They are local to a particular function.

Page 5: CPP07 - Scope

Scope• There is a process that the compiler will go through when

creating a variable.• We touched on this in an earlier lecture.

• First of all, a declaration of a variable is an instruction for the compiler.• It says to the compiler ‘Set aside some space in memory for me,

big enough to hold something of this type’• When we define a local variable, it goes to a particular

location in memory.• The stack

Page 6: CPP07 - Scope

Local Variables• When a function has finished executing, the variables are

removed from the stack.• They no longer exist, in a very real sense.

• We don’t need to do this ourselves.• C++ handles it for us.

• If we try to make use of that variable in another function, we’re making use of a variable that no longer exists in memory.• Hence the complaints.

Page 7: CPP07 - Scope

Global Variables• This contrasts to the idea of a global variable.• This is a variable that is available throughout an entire program.• It exists in memory as long as the program is running.

• Global variables are declared outside the bounds of any function in a C++ program.• Usually at the top of the file.

Page 8: CPP07 - Scope

Global Variables#include <iostream>

using namespace std;

int answer;

int add_nums (int x, int y) { answer = x + y; return answer;}

int main() { add_nums (10, 20); cout << answer << endl; return 1;}

Page 9: CPP07 - Scope

Global Variables• This program will work quite happily.• Answer is a variable available to both functions.

• We can have as many global variables as we like.• Well, within reason…

• Global variables remain in memory until the application has finished executing.

Page 10: CPP07 - Scope

Global Variables – The Good• Global variables are obviously very convenient.• No need to worry about declaring variables all the time.

• They can increase efficiency in some restricted situations.• They make your programs go faster.• None of these situations will present themselves during this

module.

Page 11: CPP07 - Scope

Global Variables – The Bad• In general, avoid global variables.• They lead to code that is unnecessarily difficult to read.• They are non-local and thus prone to manipulation outside of the

functions in which they are used.• They create unexpected side-effects.• They continue to consume memory after they have become

useless.• They reduce the reusability of your code.

Page 12: CPP07 - Scope

Local Variables – Learn To Love Them

• Local variables avoid all of these problems.• They are destroyed when they are no longer in use, saving

memory.• They cannot be accessed out of their context.• They are visible in the function in which they are defined.• You can reuse the functions directly.

• Where possible, make use of local variables only.

Page 13: CPP07 - Scope

Loop Scoping• We can restrict the scope even further by declaring counter

variables directly into a for loop.• Their scope exists only as long as the loop is executing.

• This is a syntactic nicety rather than anything else:

for (int i = 0; i < 100; i++) { cout << i << endl; }

Page 14: CPP07 - Scope

Arrays as Parameters• We talked about arrays before we talked about functions.• And thus we never touched upon the syntax for passing arrays to

functions.• The parameters you send into your functions are local

variables.• They just get their initial value set external to the function.• They have the same scoping issues.

Page 15: CPP07 - Scope

Arrays as Parameters• When we pass an array to a function in C++, we must include

the brackets.• One set of brackets to indicate dimensionality.

• We often need to pass the size of an array into the function also.• The issue of scope means that whatever mechanism we are using

to track the size of our array will be local to the function in which it is located.

Page 16: CPP07 - Scope

Arrays as Parametersint main() { int nums[10]; int size = 0; int input;

do { cin >> input;

if (input != -1) { nums[size] = input; size += 1; } } while (input != -1 & size < 10);

cout << sum_numbers (nums, size) << endl;

}

int sum_numbers (int nums[], int size) { int total;

for (int i = 0; i < size; i++) { total += nums[i]; }

return total;}

Page 17: CPP07 - Scope

Function Overloading• The last thing we are going to talk about today is the idea of

function overloading.• Not especially related to the day’s topic, but an aside.

• Functions in C++ are not uniquely identified by their name alone.

• They are identified by their name, and the type and order of their parameters.• This is known as the function signature.

Page 18: CPP07 - Scope

Function Overloading• We can provide multiple methods with the same name in a

program, as long as we have different parameter lists.• This is important for designing good programs.

• We don’t need:• add_two_ints• add_two_floats

• We provide overloaded methods

Page 19: CPP07 - Scope

Function Overloading#include <iostream>

using namespace std;

int answer;

int add_nums (int x, int y) { return x + y;}

float add_nums (float x, float y) { return x + y;}

int main() { cout << add_nums (1, 2) << endl; cout << add_nums (1.2f, 3.1f) << endl; return 1;}

Page 20: CPP07 - Scope

Function Overloading• When the compiler compiles our program, it works out which

of those methods it is going to execute by examining the provided parameters.• It executes the matching function only.

• In cases where there is ambiguity, it will give a compile time error.• In the program we saw, we need to tell c++ we are working with

floats using the 1.2f notation.

Page 21: CPP07 - Scope

Summary• Variables have scope.• This is their ‘expected lifetime’

• They are either local scope• Defined in a function

• Or global scope• Defined outside a function.

• We can overload methods.• To give us more consistent naming.