-
Notifications
You must be signed in to change notification settings - Fork 9
/
functions.c
69 lines (47 loc) · 1.4 KB
/
functions.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
#include <stdio.h>
float mySimpleFuncByValue(int iloc,float xloc)
{
iloc += 101;
xloc *= 14.6;
float yloc = (float)iloc * xloc;
return yloc;
}
float mySimpleFuncByReference(int * iPtr,float * xPtr)
{
// dereference the pointer and modify the value it points to
*iPtr += 101;
*xPtr *= 14.6;
// make copies to the values that each pointer points to
int iloc = *iPtr;
float xloc = *xPtr;
float yloc = (float)iloc * xloc;
return yloc;
}
void modifyArray( int * array )
{
array[0] = 5;
array[1] = 12;
}
int main()
{
int i = 22;
float x = 234.23;
// i and x are both passed by value,
// meaning a copy of each of these variables
// is passed to mySimpleFunc
float y = mySimpleFuncByValue(i,x);
printf("i: %d x: %10.5f y: %10.5f\n",i,x,y);
// Now i and x are both being passed by reference
// (Notice the & symbol)
// This means that the actual memory location of
// i and x are being passed, so any modifications
// to the values i and x within the function will
// propogate to main()
y = mySimpleFuncByReference(&i,&x);
printf("i: %d x: %10.5f y: %10.5f\n",i,x,y);
int myArray[2] = { 0, 0 };
printf("Before function call, myArray[0]: %d myArray[1]: %d\n",myArray[0],myArray[1]);
modifyArray(myArray);
printf("After function call, myArray[0]: %d myArray[1]: %d\n",myArray[0],myArray[1]);
return 0;
}