C - Functions
C - Functions
1
Content
2
3.1. Function Oriented Programming concept
3
3.1. Function Oriented Programming concept
child function
data with
content
Enter the coefficients Calculate delta Calculate the solution
4
Concept of function
5
Function calling
• Calling a function:
• Through its name
• Send input data (arguments) to the function through parameters
• Run the block of code with input data
• Return output data to the calling program through returned value or
parameters
B() return
call
A()
6
3.2. Function Oriented Programming in C
call stack
7
3.2.1 Function Definition
• Function Definition
• <return-type> <function-name> (<formal parameters >) {
Declare the local variables
Statements
[return statement]
}
• return statement: to exit the function and return the result of <return-
type> type to the calling program
• Each function needs one and only one definition
• It is not allowed to put function definition inside the other functions
8
3.2.1 Function Definition
• Parameters/Arguments of a function
• in function definition: formal parameters (types + dummy names) represent
values/variables supplied to the function when it is called
• in function calls: the real parameters/arguments passed to this function call
• when a function is called, each formal parameter will be evaluated and
assigned to the coresponding value: passing parameters (see later)
9
3.2.1 Function Definition
10
Organize functions in C
11
3.2.2. Parameters specification
• Parameter passing
• In C, parameters are passed by values;
• The formal parameters get value from the real parameters/arguments by
making a copy of value
• Two ways: Value type and Reference type parameter passing (next slide)
Parameter passing
Function call:
func(real parameters)
12
Value type parameter passing
13
Reference type parameter passing
14
Passing Array to function
15
Void parameter
16
3.2.3. Return type specification
17
Example
18
Example
19
Return a pointer type
• Solution 1
• int *sum(int x, int y) {
int *z = (int *)malloc(sizeof(int));
*z = x+y;
return z; int* sum() { z }
} malloc
x+y
int *p = sum(2, 3); copy
/* ... */
free(p);
p
20
3.3. Extensions
21
3.3.1 Global and local variables
• Global variable:
• declared outside of all functions
• has scope throughout the program, exists
during runtime
• accessed by all functions defined after
• Local variable:
• declared in a function or a block
• In C, local variables must be declared at the
beginning of a function or block
• accessed only inside that function / block, and
destroyed after the end of the function / block
•…
22
3.3.1 Global and local variables
• Local variable:
•…
• will "mask" other variables of the same name with a wider scope
• Function parameters/arguments are local variables of that function
• automatically allocated when the function is called
• automatically deallocated when the function returns
23
Example
25
3.3.2. Static variable
• has the same scope as a regular non-static variable (can be local or global), but
exists throughout the life of the program
• even before entering or after exiting the function/block
• Static variables are initialized only once.
• If not initialized, assigned to 0
• static keyword
• int callCount() {
static int count = 0;
count++;
return count;
}
• Global static variable: internal to that source file
• static int tic_time = 0;
void tic() {
tic_time = clock();
}
int toc() {
return clock() - tic_time;
}
26
Example
#include<stdio.h>
void func_1();
int a, b = 10;
int main()
{
func_1();
func_1();
func_1();
return 0;
}
void func_1()
{
int a = 1;
static int b = 100;
printf("a = %d\n", a);
printf("b = %d\n\n", b);
a++;
b++;
}
27
Example: Return a pointer type (cont.)
int i;
for ( i = 0; i < 10; i++) {
r[i] = rand();
}
return r;
}
28
3.3.3. Function pointer
• is a pointer to a function:
• usually used to call an unknown function
• points to the code area, not the data area
• The function name is also the function address
• An assignment can use & or not, a call can also use * or not
• Example:
• double sum(double x, double y) { return x+y; }
double prod(double x, double y) { return x*y; }
int main() {
//Declare the function pointer SomeOpt, assign it to the sum function address
double (*SomeOpt)(double, double) = ∑
return 0;
}
29
3.3.3. Function pointer
return 0;
}
30
3.3.3. Function pointer
• look-up table
void do_up_task(void) { printf("up selected\n"); }
void do_down_task(void){ printf("down selected\n");}
void do_left_task(void){ printf("left selected\n");}
void do_right_task(void){ printf("right selected\n");}
31
3.3.4. main() function
32
3.3.4. main() function
33
3.3.4. main() function
34
3.3.5. Recursive function
35
3.3.6. Macro
• Macro is a piece of code represented by a name, and each time that name
appears in the program, it will be replaced with the corresponding code
• #define ERROR { printf("Error, exit now!"); return -1; }
int main(int argc, char* argv[]) {
if (argc != 3) ERROR
/* … */
return 0;
}
• Macros can be substituted when defining another macro with the same name
• Abort the defined macro : #undef ERROR
• Check if the macro is defined
• #ifdef ERROR
/* ... */
#else
/* ... */
#endif
36
3.3.6. Macro
37
3.3.6. Macro
38
3.3.7. Project management
39
Example
40
Example
main.c myLib.h
#include <stdio.h> #define N 6
#include <stdlib.h> int gcd(int a, int b);
#include “myLib.h” float sum(float [], int );
int main(int argc, char *argv[])
{
//float sum(float [], int);
myLib.c
float x[N] = {1,3,5,7,9,11};
float y[N] = {2,4,6,8,10,12}; #include “myLib.h”
float s1 = sum (x,N); int gcd(int a, int b){
float s2 = sum (y,N); while(a!=b)
printf(“1st sum = %.0f\n”,s1); if(a>b) a -= b;
printf(“2nd sum = %.0f\n”,s2); else b -= a;
printf(“GCD is = %d\n”, return a;
gcd((int)s1,(int)s2)); }
return 0; float sum(float a[], int n){
} int i;
float sf=0;
for (i=0;i<n;i++) sf += a[i];
return sf;
}
41
Library
42
Standard libraries
Name Task
stdio.h Export, import with monitors, files, keyboards,…
ctype.h Check character classes (numbers, letters, ...)
string.h Processing strings and memory
memory.h Dynamic memory allocation and management
math.h Some math functions
stdlib.h Convert digital-string data, allocate memory,…
time.h Time functions
43
Using .h file
44
3.3.8. External variable
#include "somefile.h"
extern int var;
int main(void)
{
var = 10;
return 0;
}
45
Example
• dientich.h
• #ifndef __DIENTICH_H__
#define __DIENTICH_H__
extern const double PI; // this variable is already defined by a variable of
// the same name at the global level, in another file
double dt_tron(double r);
double dt_elip(double r1, double r2);
double dt_vuong(double l);
double dt_chu_nhat(double l1, double l2);
#endif
• dientich.c
• const double PI = 3.1415; // global declaration
double dt_tron(double r) { return r*r*PI; }
double dt_elip(double r1, double r2) { return r1*r2*PI; }
double dt_vuong(double l) { return l*l; }
double dt_chu_nhat(double l1, double l2) { return l1*l2; }
46
Bài tập
1. Viết hàm cấp phát bộ nhớ và nhập giá trị cho một mảng, trả về
con trỏ mảng và số phần tử
2. Viết hàm prime(…) trả về mảng các số nguyên tố bé hơn n
3. Viết hàm tính số Fibonacci thứ n được định nghĩa:
Fib0 = 0, Fib1 = 1
Fibn = Fibn-1 + Fibn-2 (n ≥ 2)
47
Exercises
48