TAILIEUCHUNG - Lecture Introduction to computing systems (2/e): Chapter 14 - Yale N. Patt, Sanjay J. Patel
Chapter 14 - Functions. The main contents of this chapter include all of the following: Functions in C, a function with a parameter, example: area of a ring, implementing functions in C, run-time stack, getting it all to work, tying it all together, problem solving using functions,. | Chapter 14 Functions Function Smaller, simpler, subcomponent of program Provides abstraction hide low-level details give high-level structure to program, easier to understand overall program flow enables separable, independent development C functions zero or multiple arguments passed in single result returned (optional) return value is always a particular type In other languages, called procedures, subroutines, . 14- Example of High-Level Structure main() { SetupBoard(); /* place pieces on board */ DetermineSides(); /* choose black/white */ /* Play game */ do { WhitesTurn(); BlacksTurn(); } while (NoOutcomeYet()); } Structure of program is evident, even without knowing implementation. 14- Functions in C Declaration (also called prototype) int Factorial(int n); Function call -- used in expression a = x + Factorial(f + g); type of return value name of function types of all arguments 1. evaluate arguments 2, execute function 3. use return value in expression 14- Function Definition State type, name, types of arguments must match function declaration give name to each argument (doesn't have to match declaration) int Factorial(int n) { int i; int result = 1; for (i = 1; i 14- Why Declaration? Since function definition also includes return and argument types, why is declaration needed? Use might be seen before definition. Compiler needs to know return and arg types and number of arguments. Definition might be in a different file, written by a different programmer. include a "header" file with function declarations only compile separately, link together to make executable 14- Example double ValueInDollars(double amount, double rate); main() { . dollars = ValueInDollars(francs, DOLLARS_PER_FRANC); printf("%f francs equals %f dollars.\n", francs, dollars); . } double ValueInDollars(double amount, double rate) { return amount * .
đang nạp các trang xem trước