0% found this document useful (0 votes)
6 views

C - Functions

Uploaded by

Vũ Minh Hiển
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
6 views

C - Functions

Uploaded by

Vũ Minh Hiển
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 48

Chapter 3: Function Oriented Programming

Lecturer: PhD. DO Thi Ngoc Diep


SCHOOL OF ELECTRICAL AND ELECTRONIC ENGINEERING
HANOI UNIVERSITY OF SCIENCE AND TECHNOLOGY

1
Content

• 3.1. Function Oriented Programming Concept


• Function concept
• Function calling
• 3.2. Function Oriented Programming in C
• 3.2.1. Function definition
• 3.2.2. Parameters specification
• 3.2.3. Return type specification
• 3.3. Extensions

2
3.1. Function Oriented Programming concept

• Function-oriented programming method (or structured


programming) is a method that allows to divide a program (parent
function) into smaller functions (child functions).
• can be repeated, until the functions are small enough and need not to be
divided any more (prime functions).
• Function: block of statements that perform a certain task, and can
be called as needed
• Reuse one or more times

3
3.1. Function Oriented Programming concept

• Data connection between functions


parent function

Input data Output data

child function

Solve the quadratic equation


data
without
content

data with
content
Enter the coefficients Calculate delta Calculate the solution

4
Concept of function

• Each function has to be defined before being used


• A name
• A number of parameters/arguments (can be empty): input/output data
• A returned value type: output data
• Corresponding block of statements

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

• A C program may consist of many function, but only one main()


function is mandatory.
• Recall the main() function
• is mandatory, called automatically when the program is executed
• Call to other children functions

call f1.1.1() return


f1.1()
call return
f1()
call main() return

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

• Function call: <function-name> (<real parameters/arguments>)


• can get and use the return value

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)

float sum(float m, float n){ // m and n are two dummy names


// for two formal parameters of
… // the float type
}

c = sum(a, b); // a and b are real floats passed


// to the function

9
3.2.1 Function Definition

• Prototype of a function: <return-type> <function name> (<parameters>);


• a function declaration
• provides a partial view at a function whose full definition will appear later
• the names of the parameters are not important, and can be omitted, but their data
types must be complete.
• E.g.:
• double addition(double x, double y);
double multiplication(double, double);
int main() {
double x = 5., y = 10.;
addition(x, y);
multiplication(x, y);
return 0;
}
double addition(double x, double y) { return x+y; }
double multiplication(double x, double y){ return x*y;}

10
Organize functions in C

Defined before main function

Declared before main function +


Defined later after main function

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)

Function definition: func(formal parameters)

Parameter passing

Function call:
func(real parameters)

12
Value type parameter passing

• void assign10(int x){


printf(“x = %d", x); x
x = 10; 20
}
int main() {
int a = 20; copy
assign10(a); a
printf("a = %d", a); 20
return 0;
}

• The function's parameter is a temporary/local variable, created on call


and deleted on exit of the function
• Changing the value of the parameter does not affect the original variable

13
Reference type parameter passing

void assign10(int *x){


printf(“x = %d", *x); x (int*)
*x = 10; &a
}
int main() { copy
int a = 20;
assign10(&a); a
printf("a = %d", a); &a 20  10
return 0;
}

• To change the value of the original variable, use pointer parameters


• The pointer argument is another way of returning additional value

14
Passing Array to function

• When a function parameter is a an array


• C performs no bounds checking for formal parameters
•  need to supply the size as an additional argument

void myFunction(int param[], int n)


void myFunction(int *param , int n)

15
Void parameter

• int foo(void); //explicitly takes no arguments


• int foo(); // takes an unspecified number of arguments

int foo() { return 4; } int foo(void) { return 4; }

int main() { int main() {


foo("bar"); foo("bar");
return 0; return 0;
} // compile and no warning } // error: too many arguments

16
3.2.3. Return type specification

• The function returns a value


• int find(int number, int a[], int n) {
int i;
for (i=0; i<n; i++)
if (number == a[i])
return i;
return -1;
}
• The function does not return a value: void
• void copy(int *a, int *b, int n) {
if (a==NULL || b==NULL || a==b || n==0)
return;
for (; n>0; n--)
*a++ = *b++;
}

17
Example

• Find the greatest common divisor gcd(a,b)

int gcd(int a, int b){


while(a!=b)
if(a>b) a -= b;
else b -= a;
return a;
}

void gcd(int a, int b, int* u){


while(a!=b)
if(a>b) a -= b;
else b -= a;
*u = a;
}

18
Example

• Calculate the sum of a sequence of n numbers

float sum(float a[], int N){


int i;
float sf=0;
for (i=0;i<N;i++) sf += a[i];
return sf;
}

void sum(float a[], int N, float* s){


int i;
float sf=0;
for (i=0;i<N;i++) sf += a[i];
*s = sf;
}

19
Return a pointer type

• Problem: Return a local variable int* sum() { z }


• int *sum(int x, int y) { copy
int z = x+y; address
return &z;
}

int *p = sum(2, 3); /* wrong */ p

• 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

int x = 10, y = 20;


int sum() {
int x = 1, y = 2;
int z = x+y;
int x = 10, y = 20;
return z;
int sum(int x, int y) {
}
return x+y;
int main() {
}
int z = sum();
int main() {
return 0;
int x = 100, y = 200;
}
{
int x = 1, y = 2;
int x = 10, y = 20; }
int sum() { int z = sum(x, y);
int z = x+y; return 0;
return z; }
}
int main() {
int x = 1, y = 2;
int z = sum();
return 0;
}
24
3.3.1 Global and local variables

• Variable in loop statement:


• int x = 20;
for (i=0; i<10; i++) {
int y = 20; int y ; // ???
x++; y++;
printf("%d %d\n", x, y);
}
• Has scope in one iteration of the loop
• Each iteration creates a new variable

... need to initialize the local variable to prevent undefined behavior!

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.)

• Solution 2: Use local static variable


int *getRandom( ) {
static int r[10]; // persists even after exiting the function

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) = &sum;

// Call the function by new name


SomeOpt(2., 5.); /* sum(2., 5.); */

//Change value for function pointer


SomeOpt = prod;
(*SomeOpt)(2., 5.); /* prod(2., 5.); */

return 0;
}
29
3.3.3. Function pointer

• Passing a function pointer as parameter of another function


#include <stdio.h>
int add(int x, int y);
int subtract(int x, int y);
int domath(int (*mathop)(int, int), int x, int y);

int add(int x, int y){ return x + y; }


int subtract(int x, int y){ return x - y;}
int domath(int (*mathop)(int, int), int x, int y){
return (*mathop)(x, y);
}
int main()
{
int a = domath(add, 10, 2);
printf("Add gives: %d\n", a);

int b = domath(subtract, 10, 2);


printf("Subtract gives: %d\n", b);

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");}

void (*task_list[4])(void) = { // array of function pointers


do_up_task,
do_down_task,
do_left_task,
do_right_task,
};
void main(void){
int func_number;
void (*fp)(void);
while(1)
{
printf("\nSelect a function 1-4:");
scanf("%d", &func_number);
if( (func_number > 0) && (func_number < 5) ){
fp = task_list[func_number-1];
(*fp)();
} else { return ;}
}
}

31
3.3.4. main() function

• Function required to start a C program


• Declare using one of two syntaxes:
• int main() { … }
• int main(int argc, char* argv[]) { … }

Return a value of type int Input parameters will be


passed to the program

32
3.3.4. main() function

• Input parameters will be passed to the program in command line


• argc: number of paramenters (argc ≥ 1)
• argv: array of parameters as array of string
• The path and program name are always the first parameters
• C:\>movefile abc.txt Documents
• argc: 3
• argv: [ “c:\movefile", "abc.txt", "Documents" ]

33
3.3.4. main() function

34
3.3.5. Recursive function

• A function that has a call to itself


• Ex1: factorial of a number n
• unsigned int factorial (unsigned int n) {
if (n <= 1) return 1;
return n * factorial (n-1);
}
• Ex2: x power n
• double power (double x, unsigned int n) {
double y;
if (n == 0) return 1;
y = power (x, n/2);
if (n%2 == 0) return y*y;
return y*y*x;
}
• It is not efficient when it is called many times  restrict !

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

• Macros can have parameters, sometimes used as a function


• #define MIN(x,y) x<y ? x:y
z = MIN(2,4); /* z = 2<4 ? 2:4; */
• #define PI 3.1415
#define AREA(R) R*R*PI
z = AREA(5); /* z = 5*5*3.1415; */
• Side effects
• #define MUL(x,y) x*y
z = MUL(2,4); /* z = 2*4; */
z = MUL(2+1,4); /* z = 2+1*4; */
z = 8/MUL(1+1,2); /* z = 8/1+1*2; */
• #define MUL(x,y) ((x)*(y))
z = MUL(2+1,4); /* z = ((2+1)*(4)); */
z = 8/MUL(1+1,2); /* z = 8/((1+1)*(2)); */

37
3.3.6. Macro

#define SQR(x) ((x)*(x))


int main()
{
int i = 3;
int x = SQR(i);
int z = SQR(++i); // i++
printf("i:%d, x:%d, z:%d", i, x, z);
return 0;
}

undefined behavior on different C/C++ compilers

38
3.3.7. Project management

• In C we can organize a program in two ways:


• All parts of the program in 1 file
• Split parts of a program across different files  a project
• 2 main types of files in C
• Source file "*.c": mainly contains the definitions of data and functions
• Header file ".h": usually contains data type declarations or sub-functions,
macros

39
Example

• The program calculates the sum of 2 sequences of numbers, then


finds the GCD of those 2 sums.
• main.c: contains the main() function: calls to sum function and gcd function.
• myLib.c: contains definitions of sum function and gcd function
• myLib.h: contains declarations for sum function and gcd function

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

• Some functions can be used in various programs  function libraries


• A function library consists of 2 parts:
• The header file contains the prototype of the library's usable functions
• The source file contains the definition of the function, or an .obj, .lib file if translated
into the corresponding format.
• Use the function library in a source code file :
• #include <file.h> /* in default path */
• #include "file.h" /* in the same directory as the translation file */
• The #include instruction has the effect of inserting the contents of the declared file
into the currently translated file in the position that appears

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

• In the file abcd.h


• To avoid the error of being included many times:
• #ifndef __ABCD_H__
#define __ABCD_H__
/* content of file */
#endif
• Use the file abcd.c
• #include "abcd.h" / * .h in the same directory * /
• #include <abcd.h> / * .h in library directory * /

44
3.3.8. External variable

• Code in one source file can use procedures or functions, or even


global variables in another source file.
• To share a global variable in multiple C source files, using an
external variable
• Example:
Assuming that somefile.h contains the definition of a global variable var

#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)

4. Định nghĩa kiểu chuỗi ký tự và viết thư viện một số hàm xử lý


chuỗi: khởi tạo, copy, xóa.

47
Exercises

1. Write a function that allocates memory and inputs value for an


array, returning the array pointer and the number of elements
2. Write a function prime( ) that returns an array of primes less
than n
3. Write a function that calculates the nth Fibonacci number:
Fib0 = 0, Fib1 = 1
Fibn = Fibn-1 + Fibn-2 (n ≥ 2)

4. Define a string of character type and write a library of some


string handling functions: initialize, copy, delete.

48

You might also like