Fundamentals of C++ Programming - 05: Function and Pointer - Dustin Nguyen, PhD

Solving problems with functions
❖ Understand recursive algorithms
❖ Declare and implement recursive functions
❖ Declare and using p 
pdf 77 trang xuanthi 27/12/2022 2680
Bạn đang xem 20 trang mẫu của tài liệu "Fundamentals of C++ Programming - 05: Function and Pointer - Dustin Nguyen, PhD", để tải tài liệu gốc về máy hãy click vào nút Download ở trên.

File đính kèm:

  • pdffundamentals_of_c_programming_05_function_and_pointer_dustin.pdf

Nội dung text: Fundamentals of C++ Programming - 05: Function and Pointer - Dustin Nguyen, PhD

  1. Outcomes ❖ Solving problems with functions ❖ Understand recursive algorithms ❖ Declare and implement recursive functions ❖ Declare and using pointers 2
  2. Function
  3. Function ❖ Math vs. Computer Software ❖ A function can return no value ❖ A function can take many different types of parameters ❖ A function can set as many output as it needs Input Function Output 6
  4. Function ❖ ❖ The function can return any type ❖ At some point, it must return a value ❖ return x; ❖ The function can return nothing (sometimes it is called procedure) ❖ No need for the return statement. ❖ return statement can be used to end the function. 8
  5. Function ❖ Example #include #include float add(float, float); int main() { float img[12][16]; for (int i = 0; i < 12; i++) { for (int j = 0; j < 16; j++) { img[i][j] = add(rand() % 256, (rand() % 100) * 0.01); } } return 0; } float add(float a, float b) { return a + b; } 10
  6. Function ❖ Name ❖ Many functions can have the same name: overloaded functions. ❖ Functions with the same name must not share the same prototype ❖ Function signature: name + parameter list ❖ Provide convenience for programmer 12
  7. Function ❖ Parameters: there are two ways to pass parameters to a function ❖ Value: the value will be copied to local variable (parameter) of the function ❖ Reference (only in C++): the parameter is associated with passed variable ❖ User can only pass variables through a reference parameter ❖ Any change in the parameter affects the variable 14
  8. Function ❖ main: ❖ Default return value of main: 0 - the program executed successfully ❖ stdlib.h/cstdlib: ❖ EXIT_SUCCESS: same as default return value ❖ EXIT_FAILURE: the program failed 16
  9. Function ❖ Example #include #include float add(float a, float b = 1.0f) { return a + b; } int main() { float x = 2.5; cout << “add: x + 6.08 = ” << add(x, 6.08) << endl; cout << “increase x: x + 1 = ” << add(x) << endl; return 0; } 18
  10. Function ❖ Why do you need function prototype? ❖ To reuse a function written in another module ❖ To solve tricky situations 20
  11. Scope of Variables
  12. Scope of Variables ❖ Global vs. Local variables ❖ Global variables can be accessed everywhere in the function without declaration ❖ Local variables can only be accessed inside the scope where it is declared 24
  13. Scope of Variables ❖ Global vs. Local variables ❖ Why don’t we declared everything at global scope? ❖ Benefit of local variable? ❖ When should we use global variables? ❖ When should we use local variables? 26
  14. Scope of Variables ❖ Global vs. Local variables #include #include float accSum; float acc(float a, float accSum) { ::accSum += a; return accSum + a; } int main() { accSum = 0.0f; cout << “acc(3.14159, 0): ” << acc(3.14159, 0) << endl; cout << “acc(3.14159, 1): ” << acc(3.14159, 1) << endl; cout << “accSum: ” << accSum << endl; return 0; } 28
  15. Storage ❖ How your program is organized? ❖ What are common errors? ❖ Memory overflow ❖ Memory corruption 30
  16. Storage ❖ Code segment: contains executable code (binary code) ❖ Data segment: ❖ Initialized data: global, static, constants ❖ Uninitialized data ❖ Heap: contains allocated memory at runtime ❖ Stack: stores local variables, passed arguments, and return address 32
  17. Storage ❖ Uninitialized variables #include #include float __gVal; float foo(float a, float b) { __gVal += b; return a * b + __gVal; } int main() { float x, y; x = 0.5f; cout << foo(x, y) << endl; return 0; } 34
  18. Storage ❖ Memory fault (access restricted area) #include #include char* getConstString() { return “This is a string”; } int main() { char* pStr = getConstString(); cout << pStr << endl; for (int i = 0; i < 10; i++) { pStr[i] = ‘-’; } cout << pStr << endl; return 0; } 36
  19. Storage ❖ Blow away your stack (stack overflow) #include #include int foo(int n) { return n + foo(n + 1); } int main() { cout << “This code will blow away your stack\n”; foo(0); return 0; } 38
  20. Pointer
  21. Pointer ❖ What is pointer? ❖ How do we access memory so far? ❖ Through variables: use identifiers ❖ What if you need something more dynamic? ❖ Allocate on demand ❖ Vary in size ❖ Flexible access mechanism 42
  22. Pointer ❖ Declare a pointer variable ❖ * ; ❖ E.g.: int * pInt, a; ❖ Define a pointer type ❖ typedef * ; ❖ E.g.: typedef int* intPointer; 44
  23. Pointer 3.14159 unknown #include x pX #include 3.14159 &x int main() { float x = 3.14159; float* pX; x pX pX = &x; cout << “Value of x: ” << x << endl; cout << “Address of x: ” << pX << endl; 7.853975 &x *pX *= 2.5; cout << “Value of x: ” << x << endl; pX = NULL; x pX return 0; } 7.853975 0 x pX 46
  24. Pointer ❖ Casting pointer value ❖ int *p; p = 0xff63;// error, illegal statement ❖ int *p; p = reinterpret_cast (0xff63); ❖ Use pointer wisely! 48
  25. Pointer ❖ #include Passing array as function parameter #include ❖ typedef struct { Passing values: define a new int data[10]; structure to hold array } myStruct; int foo(myStruct a) { int sum = 0; ❖ int foo(int a[10]) { for (int i = 0; i < 10; i++) sum += a.data[i]++; return sum; } } int main() { myStruct mA; ❖ int foo(int a[]) { for (int i = 0; i < 10; i++) { mA.data[i] = i; } cout << “Sum = ” << foo(mA) << endl; } return 0; } 50
  26. Pointer ❖ Pointer vs. Reference ❖ Reference is a convenient definition for pointer ❖ E.g.: int &rV = v; int *pV = &v; rV = 10; *pV -= 10; ❖ Pointer can be changed, but Reference 52
  27. Pointer ❖ Casting problem ❖ int * pointer = “Demon”; int * const const_pointer0; int * const const_pointer1 = pointer; const int * pointer_to_const; pointer = const_pointer; // OK, no cast pointer_to_const = pointer; // OK, casting from (int*) to (const int*) pointer = pointer_to_const; // Illegal const_pointer1 = “Evil”; 54
  28. Pointer ❖ Void pointer ❖ An special type of pointer representing the absent of type ❖ Declaration: void * ; ❖ Casting operations are necessary ❖ Other operations: p++; ++p; p ; p; p += N; p -= N; 56
  29. Pointer ❖ Order of operators ❖ *p++ // *(p++) ❖ *++p // *(++p) ❖ ++*p // ++(*p) ❖ (*p)++ // increase value at location pointed by p // (only valid with integer pointers) ❖ When in doubt, use safe statement. 58
  30. Pointer ❖ Allocate memory ❖ Dynamic memory: there are cases where memory needs of a program can only be determined in runtime. ❖ Common mistake: ❖ Forget release memory! (don’t be a Java programmer) ❖ Overwrite heap information by accessing outside the allocated area ❖ Overflow 60
  31. Pointer ❖ Function pointer ❖ Define function pointer type: ❖ typedef (* )( ); ❖ Easy to read and organise code ❖ E.g.: typedef int (*usrOp)(int, int); usrOp myFuncPointer; if (usrSel = 0) myFuncPointer = add; else myFuncPointer = sub; 62
  32. Recursion ❖ Problem solving methods ❖ Principle: divide the big problem into smaller problems ❖ Recursivity is a property that function have to be called by themselves. ❖ Principle: define the solution of big problem using the solution of smaller problems. A set of base solution must be defined ❖ E.g.: Fibonacci sequence is defined as follows ❖ F(n) = F(n - 1) + F(n - 2) F(1) = F(2) = 1 64
  33. Recursion ❖ More examples ❖ Simple: print a string backward ❖ Classic: Hanoi tower 66
  34. “Never hire a developer who computes the factorial using Recursion.” – Unknown recruiter
  35. Recursion ❖ Recursive method vs. Iterative method ❖ Are equally expensive: why? ❖ Where should you use recursive? ❖ Functional languages: Lisp, Scheme, Haskell, Erlang, F#, D, R, Scala, etc. ❖ Overhead: ❖ Imperative language: define function ❖ Functional language: define accumulator variable 70
  36. Fractal
  37. Extras ❖ How do you define printf, scanf? ❖ Function with variable number of arguments ❖ Standard Args (require stdarg.h) ❖ ( , ); ❖ va_list args;// declare arguments list ❖ va_start(args, var);// initialise argument list, pop first argument ❖ var = va_arg(args, );// pop next argument ❖ va_end(args);// clear argument list 74
  38. Summarise ❖ Learn about functions: how to define and use in the program ❖ How to pass parameters, understand scope of variables ❖ Memory organization of a program ❖ Pointer ❖ Recursion technique 76