Choosing Variables
The sort of procedure that you would adopt when choosing variable names is something like the following:
Decide what a variable is for and what type it needs to be.
Choose a sensible name for the variable.
Decide where the variable is allowed to exist.
Declare that name to be a variable of the chosen type.
Some local variables are only used temporarily, for controlling loops for instance. It is common to give these short names (single characters). A good habit to adopt is to keep to a consistent practice when using these variables. A common one, for instance is to use the letters: int i,j,k;
to be integer type variables used for counting. (There is not particular reason why this should be; it is just common practice.) Other integer values should have more meaningful names. Similarly names like: double x,y,z;
tend to make one think of floating point numbers.
Node:Assigning variables to one another, Next:Types and The Cast Operator, Previous:Choosing Variables, Up:Variables
Assigning variables to one another
Variables can be assigned to numbers: var = 10;
and assigned to each other: var1 = var2;
In either case the objects on either side of the = symbol must be of the same type. It is possible (though not usually sensible) to assign a floating point number to a character for instance. So int a, b = 1; a = b;
is a valid statement, and: float x = 1.4;char ch; ch = x;
is a valid statement, since the truncated value 1 can be assigned to ch. This is a questionable practice though. It is unclear why anyone would choose to do this. Numerical values and characters will interconvert because characters are stored by their ASCII codes (which are integers!) Thus the following will work: int i;char ch = 'A'; i = ch; printf ("The ASCII code of %c is %d",ch,i);
The result of this would be: The ASCII code of A is 65
Node:Types and The Cast Operator, Next:Storage class register static and extern, Previous:Assigning variables to one another, Up:Variables
Types and The Cast Operator
It is worth mentioning briefly a very valuable operator in C: it is called the cast operator and its function is to convert one type of value into another. For instance it would convert a character into an integer: int i;char ch = '\n'; i = (int) ch;
The value of the integer would be the ASCII code of the character. This is the only integer which it would make any sense to talk about in connection with the character. Similarly floating point and integer types can be interconverted: float x = 3.3;int i; i = (int) x;
The value of i would be 3 because an integer cannot represent decimal points, so the cast operator rounds the number. There is no such problem the other way around. float x;int i = 12; x = (float) i;
The general form of the cast operator is therefore: (type) variable
It does not always make sense to convert types. This will be seen particularly with regard to structures and unions. Cast operators crop up in many areas of C. This is not the last time they will have to be explained. /***************************************************//* *//* Demo of Cast operator *//* *//***************************************************/ #include main () /* Use int float and char */ { float x; int i; char ch; x = 2.345;i = (int) x;ch = (char) x;printf ("From float x =%f i =%d ch =%c\n",x,i,ch); i = 45;x = (float) i;ch = (char) i;printf ("From int i=%d x=%f ch=%c\n",i,x,ch); ch = '*';i = (int) ch;x = (float) ch;printf ("From char ch=%c i=%d x=%f\n",ch,i,x);}
Node:Storage class register static and extern, Next:Functions types, Previous:Types and The Cast Operator, Up:Variables
Storage class static and extern
Sometimes C programs are written in more than one text file. If this is the case then, on occasion, it will be necessary to get at variables which were defined in another file. If the word extern is placed in front of a variable then it can be referenced across files: File 1 File 2 int i; main () function () { { extern int i; } }
In this example, the function main() in file 1 can use the variable i from the function main in file 2.
Another class is called static. The name static is given to variables which can hold their values between calls of a function: they are allocated once and once only and their values are preserved between any number of function calls. Space is allocated for static variables in the program code itself and it is never disposed of unless the whole program is. NOTE: Every global variable, defined outside functions has the type static automatically. The opposite of static is auto.
Node:Functions types, Next:Questionsdeclare, Previous:Storage class register static and extern, Up:Variables
Functions, Types and Declarations
Functions do not always have to return values which are integers despite the fact that this has been exclusively the case up to now. Unless something special is done to force a function to return a different kind of value C will always assume that the type of a function is int.
If you want this to be different, then a function has to be declared to be a certain type, just as variables have to be. There are two places where this must be done:
The name of the function must be declared a certain type where the function is declared. e.g. a function which returns a float value must be declared as: · float function1 ()· · {· return (1.229);· }·
A function which returns a character: char function2 () { return ('*'); }
As well as declaring a function's identifier to be a certain type in the function definition, it must (irritatingly) be declared in the function in which it is called too! The reasons for this are related to the way in which C is compiled. So, if the two functions above were called from main(), they would have to declared in the variables section as: · main ()· · { char ch, function2 ();· float x, function1 ();· · x = function1 ();· ch = function2 ();· }·
If a function whose type is not integer is not declared like this, then compilation errors will result! Notice also that the function must be declared inside every function which calls it, not just main().
Node:Questionsdeclare, Previous:Functions types, Up:Variables
Questions
What is an identifier?
Say which of the following are valid C identifiers:
Ralph23
80shillings
mission_control
A%
A$
_off
Write a statement to declare two integers called i and j.
What is the difference between the types floa and double.
What is the difference between the types int and unsigned int?
Write a statement which assigns the value 67 to the integer variable "I".
What type does a C function return by default?
If we want to declare a function to return long float, it must be done in, at least, two places. Where are these?
Write a statement, using the cast operator, to print out the integer part of the number 23.1256.
Is it possible to have an automatic global variable?
Node:Parameters, Next:Scope, Previous:Variables, Up:Top
Parameters and Functions

Ways in and out of functions.
Not all functions will be as simple as the ones which have been given so far. Functions are most useful if they can be given information to work with and if they can reach variables and data which are defined outside of them. Examples of this have already been seen in a limited way. For instance the function CalculateBill accepted three values a,b and c. CalculateBill (a,b,c) int a,b,c; { int total; total = a + b + c;return total;}
When variable values are handed to a function, by writing them inside a functions brackets like this, the function is said to accept parameters. In mathematics a parameter is a variable which controls the behaviour of something. In C it is a variable which carries some special information. In CalculateBill the "behaviour" is the addition process. In other words, the value of total depends upon the starting values of a,b and c.
Parameters are about communication between different functions in a program. They are like messengers which pass information to and from different places. They provide a way of getting information into a function, but they can also be used to hand information back. Parameters are usually split into two categories: value parameters and variable parameters. Value parameters are one-way communication carrying information into a function from somewhere outside. Variable parameters are two-way.
Declaring parameters:
Value parameters:
Functions as actual parameters:
Example 2:
Example 3:
Variable parameters:
Example 4:
Qulakfj:
Node:Declaring parameters, Next:Value parameters, Previous:Parameters, Up:Parameters
Declaring Parameters
A function was defined by code which looks like this: identifier (parameters...) types of parameters { }
Parameters, like variables and functions, also have types which must be declared. For instance: function1 (i,j,x,y) int i,j;float x,y; { }
or char function2 (x,ch) double x;char ch; { char ch2 = '*'; return (ch2);}
Notice that they are declared outside the block braces.
Node:Value parameters, Next:Functions as actual parameters, Previous:Declaring parameters, Up:Parameters
Value Parameters
A value parameter is the most common kind of parameter. All of the examples up to know have been examples of value parameters. When a value parameter is passes information to a function its value is copied to a new place which is completely isolated from the place that the information came from. An example helps to show this. Consider a function which is called from main() whose purpose is to add together two numbers and to print out the result. #include main () {add (1,4);} /*******************************************/ add (a,b) int a,b; {printf ("%d", a+b);}
When this program is run, two new variables are automatically created by the language, called a and b. The value 1 is copied into a and the value 4 is copied into b. Obviously if a and b were given new values in the function add() then this could not change the values 1 and 4 in main(), because 1 is always 1 and 4 is always 4. They are constants. However if instead the program had been: main () { int a = 1, b = 4; add (a,b);} /**************************************/ add (a,b) int a,b; {printf ("%d", a+b);}
then it is less clear what will happen. In fact exactly the same thing happens:
When add() is called from main() two new variables a and b are created by the language (which have nothing to do with the variables a and b in main() and are completely isolated from them).
The value of a in main() is copied into the value of a in add().
The value of b in main() is copied into the value of b in add().
Now, any reference to a and b within the function add() refers only to the two parameters of add and not to the variables with the same names which appeared in main(). This means that if a and b are altered in add() they will not affect a and b in main(). More advanced computing texts have names for the old and they new a and b:
Actual Parameters
These are the original values which were handed over to a function. Another name for this is an argument.
Formal Parameters
These are the copies which work inside the function which was called.
Here are some points about value parameters.
The names of formal parameters can be anything at all. They do not have to be the same as the actual parameters. So in the example above it would be equally valid to write: · #include · · main ()· · { int a = 1, b = 4;· · add (a,b);· }· · /*******************************************/· · add (i,j)· · int i,j;· · {· printf ("%d", i+j);· }·
In this case the value of a in main() would be copied to the value of i in add() and the value of b in main() would be copied to the value of j in add().
The parameters ought to match by datatype when taken in an ordered sequence. It is possible to copy a floating point number into a character formal parameter, causing yourself problems which are hard to diagnose. Some compilers will spot this if it is done accidentally and will flag it as an error. e.g. · main ()· · {· function ('*',1.0);· }· · /********************************/· · function (ch,i)· · char ch;· int i;· · {· }·
is probably wrong because 1.0 is a floating point value, not an integer.
The parameters ought to, but need not match in number! This surprising fact is important because programs can go wrong if a formal parameter was missed out. ANSI C has a way of checking this by function `prototyping', but in Kernighan & Ritchie C there is no way to check this. If the number of actual parameters is more than the number of formal parameters and all of the parameters match in type then the extra values are just discarded. If the number of actual parameters is less than the number of formal parameters, then the compiler will assign some unknown value to the formal parameters. This will probably be garbage.
Our use of variables as parameters should not leave you with the impression that we can only use variables as parameters. In fact, we can send any literal value, or expression with an appropriate type to a function. For example, · sin(3.41415);· cos(a+b*2.0);· strlen("The length of this string");
Node:Functions as actual parameters, Next:Example 2, Previous:Value parameters, Up:Parameters
Functions as actual parameters
The value returned by a function can be used directly as a value parameter. It does not have to be assigned to a variable first. For instance: main () {PrintOut (SomeValue());} /*********************************************/ PrintOut (a) /* Print the value */ int a; {printf ("%d",a);} /**********************************************/ SomeValue () /* Return an arbitrary no */ {return (42);}
This often gives a concise way of passing a value to a function.
Node:Example 2, Next:Example 3, Previous:Functions as actual parameters, Up:Parameters
Example Listing/**************************************************//* *//* Value Parameters *//* *//**************************************************/ /* Toying with value parameters */ #include /**************************************************//* Level 0 *//**************************************************/ main () /* Example of value parameters */ { int i,j; double x,x_plus_one(); char ch; i = 0;x = 0; printf (" %f", x_plus_one(x));printf (" %f", x); j = resultof (i); printf (" %d",j);} /***************************************************//* level 1 *//***************************************************/ double x_plus_one(x) /* Add one to x ! */ double x; {x = x + 1;return (x);} /****************************************************/ resultof (j) /* Work out some result */ int j; {return (2*j + 3); /* why not... */}
Node:Example 3, Next:Variable parameters, Previous:Example 2, Up:Parameters
Example Listing/******************************************************//* *//* Program : More Value Parameters *//* *//******************************************************/ /* Print out mock exam results etc */ #include /******************************************************/ main () /* Print out exam results */ { int pupil1,pupil2,pupil3; int ppr1,ppr2,ppr3; float pen1,pen2,pen3; pupil1 = 87;pupil2 = 45;pupil3 = 12; ppr1 = 200;ppr2 = 230;ppr3 = 10; pen1 = 1;pen2 = 2;pen3 = 20; analyse (pupil1,pupil2,pupil3,ppr1,ppr2, ppr3,pen1,pen2,pen3); } /*******************************************************/ analyse (p1,p2,p3,w1,w2,w3,b1,b2,b3) int p1,p2,p3,w1,w2,w3;float b1,b2,b3; {printf ("Pupil 1 scored %d percent\n",p1);printf ("Pupil 2 scored %d percent\n",p2);printf ("Pupil 3 scored %d percent\n",p3); printf ("However: \n"); printf ("Pupil1 wrote %d sides of paper\n",w1);printf ("Pupil2 wrote %d sides\n",w2);printf ("Pupil3 wrote %d sides\n",w3); if (w2 > w1) { printf ("Which just shows that quantity"); printf (" does not imply quality\n"); } printf ("Pupil1 used %f biros\n",b1);printf ("Pupil2 used %f \n",b2);printf ("Pupil3 used %f \n",b3); printf ("Total paper used = %d", total(w1,w2,w3));} /*****************************************************/ total (a,b,c) /* add up total */ int a,b,c; {return (a + b + c);}
Digg Google Bookmarks reddit Mixx StumbleUpon Technorati Yahoo! Buzz DesignFloat Delicious BlinkList Furl

0 comments: on " "