Node:Example comment 2, Next:Question 7, Previous:Example comment, Up:Comments
Example 2#include
Node:Question 7, Previous:Example comment 2, Up:Comments
Question
What happens if a comment is not ended? That is if the programmer types /* .. to start but forgets the ..*/ to close?
Node:Functions, Next:Variables, Previous:Comments, Up:Top
Functions
Making black boxes. Solving problems. Getting results.
A function is a module or block of program code which deals with a particular task. Making functions is a way of isolating one block of code from other independent blocks of code. Functions serve two purposes. They allow a programmer to say: `this piece of code does a specific job which stands by itself and should not be mixed up with anyting else', and they make a block of code reusable since a function can be reused in many different contexts without repeating parts of the program text.
Functions help us to organize a program in a simple way; in Kernighan & Ritchie C they are always written in the following form: identifier (parameter1,parameter2,..) types of parameters { variable declarations statements............ }
For example Pythagoras(x,y,z) double x,y,z; { double d; d = sqrt(x*x+y*y+z*z); printf("The distance to your point was %f\n",d);}
In the newer ANSI standard, the same function is written slightly differently: Pythagoras(double x, double y, double z) { double d; d = sqrt(x*x+y*y+z*z); printf("The distance to your point was %f\n",d);}
You will probably see both styles in C programs.
Each function has a name or identifier by which is used to refer to it in a program. A function can accept a number of parameters or values which pass information from outside, and consists of a number of statements and declarations, enclosed by curly braces { }, which make up the doing part of the object. The declarations and `type of parameter' statements are formalities which will be described in good time.
The name of a function in C can be anything from a single letter to a long word. The name of a function must begin with an alphabetic letter or the underscore _ character but the other characters in the name can be chosen from the following groups:
a .. z
(any letter from a to z)
A .. Z
(any letter from A to Z)
0 .. 9
(any digit from 0 to 9)
_
(the underscore character)
This means that sensible names can easily be chosen for functions making a program easy to read. Here is a real example function which adds together two integer numbers a and b and prints the result c. All the variables are chosen to be integers to keep things simple and the result is printed out using the print-formatted function printf, from the the standard library, with a "%d" to indicate that it is printing a integer. Add_Two_Numbers (a,b) /* Add a and b */ int a,b; { int c; c = a + b;printf ("%d",c); }
Notice the position of the function name and where braces and semi-colons are placed: they are crucial. The details are quickly learned with practice and experience.
This function is not much use standing alone. It has to be called from somewhere. A function is called (i.e. control is passed to the function) by using its name with the usual brackets () to follow it, along with the values which are to be passed to the function: main () { int c,d; c = 1;d = 53; Add_Two_Numbers (c,d);Add_Two_Numbers (1,2); }
The result of this program would be to print out the number 54 and then the number 3 and then stop. Here is a simple program which makes use of some functions in a playful way. The structure diagram shows how this can be visualized and the significance of the program `levels'. The idea is to illustrate the way in which the functions connect together:
Structure diagram:
Program listing:
Functions with values:
Breaking out early:
The exit function:
Functions and types:
Questions 6:
Node:Structure diagram, Next:Program listing, Previous:Functions, Up:Functions
Structure diagramLevel 0: main () Level 1: DownOne () / \ / \ Level 2: DownLeft() DownRight()
Note: not all functions fit into a tidy hierarchy like these. Some functions call themselves, while others can be called from anywhere in a program. Where would you place the printf function in this hierarchy?
Node:Program listing, Next:Functions with values, Previous:Structure diagram, Up:Functions
Program Listing/***********************************************//* *//* Function Snakes & Ladders *//* *//***********************************************/ #include
Node:Functions with values, Next:Breaking out early, Previous:Program listing, Up:Functions
Functions with values
In other languages and in mathematics a function is understood to be something which produces a value or a number. That is, the whole function is thought of as having a value. In C it is possible to choose whether or not a function will have a value. It is possible to make a function hand back a value to the place at which it was called. Take the following example: bill = CalculateBill(data...);
The variable bill is assigned to a function CalculateBill() and data are some data which are passed to the function. This statement makes it look as though CalculateBill() is a number. When this statement is executed in a program, control will be passed to the function CalculateBill() and, when it is done, this function will then hand control back. The value of the function is assigned to "bill" and the program continues. Functions which work in this way are said to return a value.
In C, returning a value is a simple matter. Consider the function CalculateBill() from the statement above: CalculateBill(starter,main,dessert) /* Adds up values */ int starter,main,dessert; { int total; total = starter + main + dessert;return (total);}
As soon as the return statement is met CalculateBill() stops executing and assigns the value total to the function. If there were no return statement the program could not know which value it should associate with the name CalculateBill and so it would not be meaningful to speak of the function as having one value. Forgetting a return statement can ruin a program. For instance if CalculateBill had just been: CalculateBill (starter,main,dessert) /* WRONG! */ int starter,main,dessert; { int total; total = starter + main + dessert;}
then the value bill would just be garbage (no predictable value), presuming that the compiler allowed this to be written at all. On the other hand if the first version were used (the one which did use the return(total) statement) and furthermore no assignment were made: main () {CalculateBill (1,2,3);}
then the value of the function would just be discarded, quite legitimately. This is usually what is done with the input output functions printf() and scanf() which actually return values. So a function in C can return a value but it does not have to be used; on the other hand, a value which has not been returned cannot be used safely.
NOTE : Functions do not have to return integers: you can decide whether they should return a different data type, or even no value at all. (See next chapter)
Node:Breaking out early, Next:The exit function, Previous:Functions with values, Up:Functions
Breaking out early
Suppose that a program is in the middle of some awkward process in a function which is not main(), perhaps two or three loops working together, for example, and suddenly the function finds its answer. This is where the beauty of the return statement becomes clear. The program can simply call return(value) anywhere in the function and control will jump out of any number of loops or whatever and pass the value back to the calling statement without having to finish the function up to the closing brace }. myfunction (a,b) /* breaking out of functions early */ int a,b; {while (a <> b) { return (b); } a = a + 1; }}
The example shows this. The function is entered with some values for a and b and, assuming that a is less than b, it starts to execute one of C's loops called while. In that loop, is a single if statement and a statement which increases a by one on each loop. If a becomes bigger than b at any point the return(b) statement gets executed and the function myfunction quits, without having to arrive at the end brace }, and passes the value of b back to the place it was called.
Node:The exit function, Next:Functions and types, Previous:Breaking out early, Up:Functions
The exit() function
The function called exit() can be used to terminate a program at any point, no matter how many levels of function calls have been made. This is called with a return code, like this: #define CODE 0 exit (CODE);
This function also calls a number of other functions which perform tidy-up duties such as closing open files etc.
Node:Functions and types, Next:Questions 6, Previous:The exit function, Up:Functions
Functions and Types
All the variables and values used up to now have been integers. But what happens if a function is required to return a different kind of value such as a character? A statement like: bill = CalculateBill (a,b,c);
can only make sense if the variable bill and the value of the function CalculateBill() are the same kind of object: in other words if CalculatBill() returns a floating point number, then bill cannot be a character! Both sides of an assignment must match.
In fact this is done by declaring functions to return a particular type of data. So far no declarations have been needed because C assumes that all values are integers unless you specifically choose something different. Declarations are covered in the next section.
Node:Questions 6, Previous:Functions and types, Up:Functions
Questions
Write a function which takes two values a and b and returns the value of (a*b).
Is there anything wrong with a function which returns no value?
What happens if a function returns a value but it is not assigned to anything?
What happens if a function is assigned to an object but that function returns no value?
How can a function be made to quit early?
Node:Variables, Next:Parameters, Previous:Functions, Up:Top
0 comments: on " "
Post a Comment