(As a first time reader you may wish to omit this section until you have read about Pointers and Operators.)
One way to hand information back is to use the return statement. This function is slightly limited however in that it can only hand the value of one variable back at a time. There is another way of handing back values which is less restrictive, but more awkward than this. This is by using a special kind of parameter, often called a variable parameter. It is most easily explained with the aid of an example: #include
To understand fully what is going on in this program requires a knowledge of pointers and operators, which are covered in later sections, but a brief explanation can be given here, so that the method can be used.
There are two new things to notice about this program: the symbols & and *. The ampersand & symbol should be read as "the address of..". The star * symbol should be read as "the contents of the address...". This is easily confused with the multiplication symbol (which is identical). The difference is only in the context in which the symbol is used. Fortunately this is not ambiguous since multiplication always takes place between two numbers or variables, whereas the "contents of a pointer" applies only to a single variable and the star precedes the variable name.
So, in the program above, it is not the variables themselves which are being passed to the procedure but the addresses of the the variables. In other words, information about where the variables are stored in the memory is passed to the function GetValues(). These addresses are copied into two new variables p and q, which are said to be pointers to i and j. So, with variable parameters, the function does not receive a copy of the variables themselves, but information about how to get at the original variable which was passed. This information can be used to alter the "actual parameters" directly and this is done with the * operator. *p = 10;
means: Make the contents of the address held in p equal to 10. Recall that the address held in p is the address of the variable i, so this actually reads: make i equal to 10. Similarly: *q = 20;
means make the contents of the address held in q equal to 20. Other operations are also possible (and these are detailed in the section on pointers) such as finding out the value of i and putting it into a new variable, say, a: int a; a = *p; /* is equivalent to a = i */
Notice that the * symbol is required in the declaration of these parameters.
Node:Example 4, Next:Qulakfj, Previous:Variable parameters, Up:Parameters
Example Listing/**************************************************//* *//* Program : Variable Parameters *//* *//**************************************************/ /* Scale some measurements on a drawing, say */ #include
Node:Qulakfj, Previous:Example 4, Up:Parameters
Questions
Name two ways that values and results can be handed back from a function.
Where are parameters declared?
Can a function be used directly as a value parameter?
Does it mean anything to use a function directly as a variable parameter?
What do the symbols * and & mean, when they are placed in front of an identifier?
Do actual and formal parameters need to have the same names?
Node:Scope, Next:Preprocessor, Previous:Parameters, Up:Top
Scope : Local And Global
Where a program's fingers can't reach.
From the computer's point of view, a C program is nothing more than a collection of functions and declarations. Functions can be thought of as sealed capsules of program code which float on a background of white space, and are connected together by means of function calls. White space is the name given to the white of an imaginary piece of paper upon which a program is written, in other words the spaces and new line characters which are invisible to the eye. The global white space is only the gaps between functions, not the gaps inside functions. Thinking of functions as sealed capsules is a useful way of understanding the difference between local and global objects and the whole idea of scope in a program.
Another analogy is to think of what goes on in a function as being like watching a reality on television. You cannot go in and change the TV reality, only observe the output, but the television show draws its information from the world around it. You can send a parameter (e.g. switch channels) to make some choices. A function called by a function, is like seeing someone watching a televsion, in a television show.
Global variables:
Local variables:
Parameters again:
Example 5:
Style note:
Scope and style:
Questions 11:
Node:Global variables, Next:Local variables, Previous:Scope, Up:Scope
Global Variables
Global variables are declared in the white space between functions. If every function is a ship floating in this sea of white space, then global variables (data storage areas which also float in this sea) can enter any ship and also enter anything inside any ship (See the diagram). Global variables are available everywhere;. they are created when a program is started and are not destroyed until a program is stopped. They can be used anywhere in a program: there is no restriction about where they can be used, in principle.
Node:Local variables, Next:Parameters again, Previous:Global variables, Up:Scope
Local Variables
Local variables are more interesting. They can not enter just any region of the program because they are trapped inside blocks. To use the ship analogy: if it is imagined that on board every ship (which means inside every function) there is a large swimming pool with many toy ships floating inside, then local variables will work anywhere in the swimming pool (inside any of the toys ships, but can not get out of the large ship into the wide beyond. The swimming pool is just like a smaller sea, but one which is restricted to being inside a particular function. Every function has its own swimming pool! The idea can be taken further too. What about swimming pools onboard the toy ships? (Meaning functions or blocks inside the functions! /* Global white space "sea" */ function () {/* On board ship */ { /* On board a toy ship */ }}
The same rules apply for the toy ships. Variables can reach anywhere inside them but they cannot get out. They cannot escape their block braces {}. Whenever a pair of block braces is written into a program it is possible to make variable declarations inside the opening brace. Like this: { int locali; char localch; /* statements */ }
These variables do not exist outside the braces. They are only created when the opening brace is encountered and they are destroyed when the closing brace is executed, or when control jumps out of the block. Because they only work in this local area of a program, they are called local variables. It is a matter of style and efficiency to use local variables when it does not matter whether variables are preserved outside of a particular block, because the system automatically allocates and disposes of them. The programmer does not have to think about this.
Where a variable is and is not defined is called the scope of that variable. It tells a programmer what a variables horizons are!
Node:Parameters again, Next:Example 5, Previous:Local variables, Up:Scope
Communication : parameters
If functions were sealed capsules and no local variables could ever communicate with other parts of the program, then functions would not be very useful. This is why parameters are allowed. Parameters are a way of handing local variables to other functions without letting them out! Value parameters (see last section) make copies of local variables without actually using them. The copied parameter is then a local variable in another function. In other words, it can't get out of the function to which is it passed ... unless it is passed on as another parameter.
Node:Example 5, Next:Style note, Previous:Parameters again, Up:Scope
Example Listing
Notice about the example that if there are two variables of the same name, which are both allowed to be in the same place (c in the example below) then the more local one wins. That is, the last variable to be defined takes priority. (Technically adept readers will realize that this is because it was the last one onto the variable stack.) /***************************************************************//* *//* SCOPE : THE CLLLED CAPSULES *//* *//***************************************************************/ #include
Node:Style note, Next:Scope and style, Previous:Example 5, Up:Scope
Style Note
Some programmers complain about the use of global variables in a program. One complaint is that it is difficult to see what information is being passed to a function unless all that information is passed as parameters. Sometimes global variables are very useful however, and this problem need not be crippling. A way to make this clear is to write global variables in capital letters only, while writing the rest of the variables in mainly small letters.. int GLOBALINTEGER; .... { int local integer; }
This allows global variables to be spotted easily. Another reason for restricting the use of global variables is that it is easier to debug a program if only local variables are used. The reason is that once a function capsule is tested and sealed it can be guaranteed to work in all cases, provided it is not affected by any other functions from outside. Global variables punch holes in the sealed function capsules because they allow bugs from other functions to creep into tried and tested ones. An alert and careful programmer can usually control this without difficulty.
The following guidelines may help the reader to decide whether to use local or global data:
Always think of using a local variable first. Is it impractical? Yes, if it means passing dozens of parameters to functions, or reproducing a lot of variables. Global variables will sometimes tidy up a program.
Local variables make the flow of data in a program clearer and they reduce the amount of memory used by the program when they are not in use.
The preference in this book is to use local variables for all work, except where a program centres around a single data structure. If a data structure is the main reason for a program's existence, it is nearly always defined globally.
Node:Scope and style, Next:Questions 11, Previous:Style note, Up:Scope
Scope and Style
All the programs in this book, which are longer than a couple of lines, are written in an unusual way: with a levelled structure There are several good reasons for this. One is that the sealed capsules are shown to be sealed, by using a comment bar between each function. /**************************************/
Another good reason is that any function hands parameters down by only one level at a time and that any return() statement hands values up a single level. The global variables are kept to a single place at the head of each program so that they can be seen to reach into everything.
The diagram shows how the splitting of levels implies something about the scope of variables and the handing of parameters.
Node:Questions 11, Previous:Scope and style, Up:Scope
Questions
What is a global variable?
What is a local variable?
What is meant by calling a block (enclosed by braces {} ) a "sealed capsule"?
Do parameters make functions leaky? i.e. Do they spoil them by letting the variables leak out into other functions?
Write a program which declares 4 variables. Two integer variables called number_of_hats,counter which are GLOBAL and two float variables called x_coord,y_coord which are LOCAL inside the function main(). Then add another function called another() and pass x_coord,y_coord to this function. How many different storage spaces are used when this program runs? (Hint: are x_coord,y_coord and their copies the same?)
0 comments: on " "
Post a Comment