1 ipc144 session 14 the c programming language. 2 objectives predict the automatic conversion of...
TRANSCRIPT
1
IPC144Session 14
The C Programming Language
2
Objectives
Predict the automatic conversion of data types using the promotion hierarchyUse the promotion hierarchy to determine the stored result of a calculationDefine the purpose of the cast operatorUse the cast operator to override automatic conversions of data types.To name the elements of a function declarationTo construct a function declaration and its prototypeTo differentiate between Pass-by-reference and Pass-by-valueTo declare a function that is capable of altering contents of a variable in the calling module
3
The C Language
PromotionIn the C coding examples presented so far, the data types have been consistent. All of the variables are floats or they are ints.
We have performed the calculations without being concerned with side-effects.
What happens when we begin mixing data types inside of calculations?
1) In the C language, when we have operands of different types, the operands are converted to the more general type (i.e. they are converted to the data type of the operand that can contain the larger maximum value). The final result is expressed using the more general data type.
2) Regardless of the data types of the operands on the right side of the assignment operator- the result is converted to the data type of the variable receiving the result (There may be a loss of precision).
Based on these rules, what would be the output of the following code?
4
The C Language
Promotion, continued#include <stdio.h>int main(void){ int i; int j; int k; float x; float y; float z;
i = 5; j = 3; x = 5.0; y = 3.0;
k = i / j; printf("int / int assigned to an int => %d\n", k); z = x / y; printf("float / float assigned to a float => %f\n", z); z = i / j; printf("int / int assigned to a float => %f\n", z); k = x / y; printf("float / float assigned to an int => %d\n", k); z = i / y; printf("int / float assigned to a float => %f\n", z); k = i / y; printf("int / float assigned to a int => %d\n", k);}
The C Language
Promotion, continued
As there is a requirement toconvert from one data type toanother, all variables areconverted to the variable'sdata type that is highest onthis scale.
5char
short int
int
unsignedint
long int
unsignedlong int
float
double
longdouble
Promoti
on H
ierarc
hy
The C Language
CastingThere is a means to force a variable or expression to behave like a specific data type. This is referred to as casting.
The cast operator is simply the desired data type in parenthesis, placed just prior to the target variable.
For example, if I wanted an integer data type to behave like a float, then I would place (float) in front of the variable or expression.
Recall from the programming example:
z = i / j; printf("int / int assigned to a float => %f\n", z);
resulted in:
int / int assigned to a float => 1.000000
6
The C Language
Casting, continuedWhat if we altered the code slightly. What would be the result of:
z = (float)i / (float)j; printf("int / int assigned to a float => %f\n", z);
7
8
The C Language
Modules (and Functions)Recall that when a program calls a module, it passes data to it. The module performs its function, and returns to the originating program right where it left off.
How does the computer know where it needs to resume execution after completing the module?
How do those data elements get passed to the module?
-> The Stack
9
The C Language
The StackThe stack is a special purpose segment of memory that is used to keep track of a program's execution. It behaves like a queue.
There are two types of stacks or queues:
FIFO - First In First OutLIFO - Last In First Out
(all of the above are not to be confused with GIGO - Garbage In Garbage Out, a programmer's way of saying "if the input data is faulty, your output will be faulty").
10
The C Language
FIFOFirst In First Out-this is like a line up at a grocery check-out counter. The first person to arrive will be the first person serviced, and therefore the first to leave.
11
The C Language
LIFOLast In First Out- this is 'like' an elevator. The first people in move to the back of the elevator, the last person in is in front of the the elevator door. As the elevator makes stops on its way to the destination, more people will be pushing the first people further back. The last person in will be the first person out when the elevator reaches its destination.
The stack in the computer is a LIFO type stack.
12
The C Language
Terminology of the StackThere are common terms used when dealing with stacks:
Push: to place an item onto the stackPop: to remove an item from the stack
13
The C Language
Procedures and FunctionsBy definition Procedures and Functions are different animals.
Procedures - allow for their parameters to be altered
Functions - do not allow their parameters to be altered, but return a value to the calling program
The C language does not make this distinction, and allows for both modifiable parameters as well as return values.
14
The C Language
Procedures and Functions, continuedHow do we code a function in C?
Have we seen any yet?
15
The C Language
Procedures and Functions, continued
int main(void){ . . . }
This is a function that we have already seen.
16
The C Language
Procedures and Functions, continuedAnatomy of a C function:
dataType functionName(parameters){
}
The parameters are those variables being passed to the function (to possible be modified)
The name of the function - use the same standards for function names as for variable names
If the function will return something other than an integer, the data type must be specifiedThe braces block off the function's code and must be there even if the function is one line long
17
The C Language
Procedures and Functions, continueddataType functionName(parameters)
A function can return a value other than what is defined in the parameter list- this is the purpose of the dataType in the function declaration.
By default, if the data type has not been specified, the function returns an int.
All of the data types we have declared (int, float, char, double...) are supported
One additional data type is allowed: void
The void data type indicates that the function will not return a value
When you use void as the parameter list, it tells the computer that there are no parameters
18
The C Language
Procedures and Functions, continueddataType functionName(parameters)
What is the advantage to returning a value that is not in the parameter list?
A status value can be returned without having to explicitly state it in the parameter list (programmers are by their very nature lazy).Other programmers may choose to use or not use the status information that you are providingThe function can be used in the midst of a calculation
19
The C Language
Procedures and Functions, continueddataType functionName(parameters)
The parameters list, lists the variables that are to be used in the function.
These variables are ALIASES - they don't actually exist outside of your function
If you use a variable name in one function, you can use the same name in another function, and the compiler will treat them as different variables
It is like having two John Smiths - the name is the same but the people are different
20
The C Language
Procedures and Functions, continueddataType functionName(parameters)
As mentioned before, when defining a parameter list you may use void to indicate that there are no parameters being passed.
For the variables that are in the list, you must specify their data type so that the compiler knows how to treat them.
The values that are passed to the function are COPIES of the actual variable values from the calling module - this is called PASSING BY VALUE
21
The C Language
Procedures and Functions, continuedExample:
. . .
int roundOff(float a, int direction){ if (direction == ROUND_UP) a = a + 0.5;
return a;}
The return statement is how the function can return a value to the calling program that is not explicitly in its parameter list
A little like the expressions we have looked at. Upon completion the function becomes the value of the return statement
22
The C Language
Procedures and Functions, continuedWhat is a function prototype? (other than a new term to remember)
A function prototype is simply the declaration of the function (data type, function name, parameters) placed at the beginning of the source code file, with a semicolon at the end (the function prototype is therefore a C statement)
Some compilers insist on function prototypes and will give you a lot of grief if they are absent.
The compiler will use the function prototype to ensure that you are consistent throughout your code as to data types and parameters being used in your functions.
The variable names in the function prototype do not need to match the names in the actual function declaration.int myFunc(int a, float b, double c);
int myFunc(int x, float y, double z){}
23
The C Language
Procedures and Functions, continuedCoding Standards and Guidelines for Functions/Procedures
Function prototypes must be generated for all functions
The variable list in the function prototype should match the variable list in the function declaration.
The return data type of the function must be explicitly declared (you may not rely on C treating functions as return type int).
The handling of the braces is the same as for the if and while statements
24
The C Language
Procedures and Functions, continued#include <stdio.h>
#define ROUND_UP 1#define ROUND_DOWN 0
int roundOff(float a, int direction);
int main(void){ float num; int newNum;
printf("Enter a number to be rounded off: "); scanf("%f", &num); newNum = roundOff(num, ROUND_UP); printf("%f Rounded is: %d\n", num, newNum);}
int roundOff(float a, int direction){ if (direction == ROUND_UP) a = a + 0.5;
return a;}
25
The C Language
Bringing it all TogetherRecall pointers:Address-of operator: &Indirection operator: *
The Stack:LIFO
Much of the reason why referencing the address of a variable is so important deals with how C passes variables to functions.
26
The C Language
Bringing it all Together, continuedWhat happens when you invoke a function?
Some program information is pushed on the stack (where to start running when the function finishes, CPU register information...)The variables that are being PASSED BY VALUE are also pushed onto the stackWhen the new function begins to run, it pops the values for the variables off the stackThe function does what it has been programmed to do, then upon completion,The computer pops the remaining information off the stack which restores the CPU information and the memory address of the next opcode to be executed in the calling function.
27
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j);
int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
28
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j);
int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
i = 13
j = 3
29
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j);
int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
i = 13
j = 3
A704
13
3
30
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j);
int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
i = 13
j = 3
A704
p = 13
q = 3
k =
31
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j); int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
i = 13
j = 3
A704
p = 13
q = 3
k = 39
32
The C Language
Bringing it all Together, continued #include <stdio.h>
void printMult(int i, int j);
int main(void) { int i; int j; A701 i = 13;A702 j = 3;
A703 printMult(i, j);A704 printf("done\n"); }
void printMult(int p, int q) { int k; A705 k = p * q;A706 printf("mult is %d\n", k); }
The Stack Memory
0
1
2
3
4
5
6
7
i = 13
j = 3
33
The C Language
Bringing it all TogetherWhat would happen if the value we needed to pass was huge (perhaps a few megabytes)?
We might overflow the stack (the stack might be only 8KB in size)
What if we wanted to change the value of one of the parameters, and have it affect the original copy of the variable?
In these circumstances, we would be better off telling the function we are calling WHERE to find the data so that it might go ahead and modify it directly.
What mechanism, or C operators, provide us this functionality?
34
The C Language
C Functions and pointersNormally when we call a function, we can pass VALUES to the function. This is called 'Pass-by-value'.
For example, the printf() function that we have been using. Since we don't need to change the contents of the variables that are supplying the information- we only care about the VALUES so that we can output them.
35
The C Language
C Functions and pointers, continuedInstead of accepting a value and performing some operation on it, what if we wanted the ability to change the variable from within the function?
For example, the scanf() function. Pass-by-value will pass the current value of the variable to the scanf() function. The scanf() function will get a new value, but has no way of returning it to the calling function.
What prevents us from altering the contents of the variables directly when we use pass-by-value?
36
The C Language
C Functions and pointers, continuedThe only way to get around the problem of the stack isolating us from the original variables is to place the address of the variable we wish to change on to the stack.
Since the address is always available using the address-of operator (&), we don't care if this value has been lost when the stack returns from the function call.
Since we are passing a reference to a variable, instead of a value, this technique is referred to as Pass-by-reference.
37
The C Language
C Functions and pointers, continuedWhile we are in the function, we use the Indirection Operator (*) to access the memory location of the variable directly.
So, when you write a function that is to be used to change the contents of variable(s) in its parameter list, you must be careful to use the & and * operators correctly.
38
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
39
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
} void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 5
yourVar = 10
40
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 5
yourVar = 10
A705
0000
10
41
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 5
yourVar = 10
A705
valA = 0000
valB = 10
42
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 10
yourVar = 10
A705
valA = 0000
valB = 10
43
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 10
yourVar = 10
A705
valA = 0000
valB = 20
44
The C Language
C Functions and pointers, continued #include <stdio.h>
void exampleFunction(int *valA, int valB);
int main(void) { int myVar; int yourVar; A701 myVar = 5;A702 yourVar = 10;
A703 printf("1) myVar %d yourVar%d\n", myVar, yourVar);
A704 exampleFunction(&myVar, yourVar);
A705 printf("2) myVar %d yourVar%d\n", myVar, yourVar);
}
void exampleFunction(int *valA, int valB) {A706 *valA = valB;A707 valB = 2 * valB; }
The Stack Memory
0
1
2
3
4
5
6
7
myVar = 10
yourVar = 10
45
The C Language
C Functions and pointers, continuedOne thing to remember: a pointer is a pointer is a pointer, which means that once a pointer, always a pointer
Keep track of your variables- which ones are pointers and which ones are not
Remember from our coding standards that you must use conventional abbreviations
For pointers, the conventional abbreviation is ptr
46
The C Language
C Functions and pointers, continuedWhat is the output of:#include <stdio.h>
void someFunction(int *a, float *b);
int main(void){ float myFloat; int someInt; int *ptrSomeInt; float *ptrMyFloat;
myFloat = 10.0; someInt = 20; printf("1) myFloat=%1.2f someInt=%d\n", myFloat, someInt);
ptrSomeInt = &someInt; ptrMyFloat = &myFloat;
someFunction(ptrSomeInt, ptrMyFloat); printf("2) myFloat=%1.2f someInt=%d\n", myFloat, someInt);}void someFunction(int *a, float *b){ *b = 15.5; *a = 25;}
47
The C Language
C Functions and pointers, continuedWrite a main function that reads two integers from the user and prints them on the screen.
48
The C Language
C Functions and pointers, continuedModify the program. Add a function that swaps the values that are in the variables containing the values the user entered. After calling the function, print out the contents of the variables (copy the printf() statement).
E.g. Assume the first variable contains 5, and the second variable contains 7. When the swap function returns, the first variable will contain 7, and the second variable will contain 5.