1 Functions (covered by Chapter 5 in ABC). 2 Type function_name( parameter list ) { Declarations Statements } Function Definition Header body Partitioning.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Overview of programming in C C is a fast, efficient, flexible programming language Paradigm: C is procedural (like Fortran, Pascal), not object oriented.
C Language.
Core Java Lecture 4-5. What We Will Cover Today What Are Methods Scope and Life Time of Variables Command Line Arguments Use of static keyword in Java.
BBS514 Structured Programming (Yapısal Programlama)1 Functions and Structured Programming.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
1 Review of Class on Oct Outline  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Review of Class on Oct Outline of Chapter 4  How to write a function?  Function Prototypes  Function Invocation  Function Definition  The.
Runtime Environments Source language issues Storage organization
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
1 Lecture 6  Functions  C Standard Libraries  Invocation  Definition  Call-by-value  Prototype  Multi-file program  Macros  Readings: Chapter.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
1 Chapter 4 (II) Functions and Structured Programming.
1 Chapter 8 Functions, Pointers, and Storage Classes  Pointer  Pointers to void  Call-by-Reference  Basic Scope Rules  Storage Classes  Default Initialization.
1 Review of Chapter 6: The Fundamental Data Types.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Runtime Environments Compiler Construction Chapter 7.
Compiler Construction
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
CSCI 130 Chapter 5 Functions. Functions are named uniquely Performs a specific task Is independent –should not interfere with other parts of program May.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
ECE 103 Engineering Programming Chapter 36 C Storage Classes Herbert G. Mayer, PSU CS Status 8/4/2014 Initial content copied verbatim from ECE 103 material.
Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
CCSA 221 Programming in C CHAPTER 8 – PART 1 WORKING WITH FUNCTIONS 1.
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
1 Unstructured Programming The Need for Procedures/Functions Procedural Programming Function Declaration/Prototypes/Invocation Example Functions Function.
Functions. Motivation What is a function? A function is a self-contained unit of program code designed to accomplish a particular task. We already used.
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Modularity using Functions Chapter 4. Modularity In programming blocks of code often can be "called up" and reused whenever necessary, for example code.
1 ICS103 Programming in C Lecture 8: Functions I.
1 Run-Time Environments Chapter 7 COP5621 Compiler Construction Copyright Robert van Engelen, Florida State University, 2005.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
Functions. Flow of Control Review while for do while goto break & continue switch Relational operators short circuits.
LECTURE 3 Translation. PROCESS MEMORY There are four general areas of memory in a process. The text area contains the instructions for the application.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Code Generation Instruction Selection Higher level instruction -> Low level instruction Register Allocation Which register to assign to hold which items?
Lecture 3 Translation.
Chapter 9: Value-Returning Functions
Run-Time Environments Chapter 7
User-Written Functions
Chapter 7: User-Defined Functions II
Computer Science 210 Computer Organization
Functions, Part 2 of 2 Topics Functions That Return a Value
Functions and Structured Programming
Functions.
User-Defined Functions
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
Computer Science 210 Computer Organization
CSC 253 Lecture 8.
CSC 253 Lecture 8.
CSI-121 Structured Programming Language Lecture 14 Functions (Part 2)
Functions I Creating a programming with small logical units of code.
Lecture 18 Arrays and Pointer Arithmetic
Functions, Part 2 of 3 Topics Functions That Return a Value
Multiple Files Revisited
Functions I Creating a programming with small logical units of code.
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Functions.
Presentation transcript:

1 Functions (covered by Chapter 5 in ABC)

2 Type function_name( parameter list ) { Declarations Statements } Function Definition Header body Partitioning the code into functions makes it more readable and self-documenting

3 Runtime Stack return value actual parameters f2()control link activationsaved machine status recordlocal data temporaries return value actual parameters f1()control link activationsaved machine status recordlocal data temporaries return value actual parameters main()control link activationsaved machine status recordlocal data temporaries Activation records / stack frames are created and stored in an area of memory termed the runtime stack. void f2(char c, int i){... } void f1(int i){... f2('a', i);... } int main(void){ f1(1); return 0; }

4 Storage Organization The program stack grows each time a function call is made. Infinite recursion results in a collision between the runtime stack and the heap termed a run- time stack overflow error. Illegal pointer de-references (garbage, dangling-references) often result in memory references outside the operating system allocated partition, (segment) for the C program resulting in a segmentation error (GPF - access violation) and core dump. System Privileges (not accessible to the C program) Binary Code Static Data Runtime Stack Function activation record management Dynamic memory structure management Heap Typical C program execution memory model

5 double abs_value( double x ) { if ( x >= 0.0 ) return x; else return -x; } Conversions No use of return value The stack mechanism The return statement The evaluated value is returned return; return ++a; return (a * b);

6 double sqrt( double ); void f(char c, int i); is equivalent to: void f(char, int); Function Prototypes When declaring a function, the names of the input parameters do not matter, only their type and order.

7 #include #define N 7 long power( int, int ); void prn_heading( void ); void prn_tbl_of_powers( int ); int main(void) { prn_heading(); prn_tbl_of_powers( N ); return 0; } Functions Example Function declaration (Prototypes) Using the functions

8 Functions Example void prn_heading( void ) { printf( “\n::::: A TABLE OF POWERS :::::\n\n” ); } long power( int m, int n) { int i = 0; long product = 1; for ( i = 1; i <= n; ++i ) product *= m; return product; }

9 Functions Example void prn_tbl_of_powers( int n ) { int i = 0, j = 0; for ( i = 1; i <= n; ++i ) { for ( j = 1; j <= n; ++j ) { if ( j == 1 ) printf( “%ld”, power( i, j ) ); else printf( “%9ld”, power( i, j ) ); } putchar( ‘\n’ ); } ::::: A TABLE OF POWERS ::::: …..

10 #include int main( void ) { int n = 3, sum = 0, compute_sum( int ); printf( “%d\n”, n ); sum = compute_sum( n ); printf( “%d\n”, n ); printf( “%d\n”, sum ); return 0; } what happens to n and sum here? Call by Value Function declaration 3 is printed 6 is printed

11 Call by Value int compute_sum( int n ) { int sum = 0; for ( ; n > 0; --n ) sum += n; return sum; } sum the integers from 1 to n This n is local. It gets the value of the of the varuable that was sent to the function. sum is local to the function and. local n and sum are changed

12 Function invocation - summary 1.Each expression in the argument list is evaluated. 2.The value of the expression is converted, if necessary, to the type of the formal parameter, and is assigned to its corresponding formal parameter ("call by value") at the beginning of the function's body. 3.The body of the function is executed. 4.If a 'return' statement is executed, then control is passed back to the calling environment. 5.If the 'return' statement includes an expression then the value of the expression is converted, if necessary, to the type given by the type specifier of the function, and that value is passed to the calling environment as well. 6.If the 'return' statement does not include an expression, no useful value is returned. 7.If no 'return' statement is present, control is passed back to the calling environment at the end of the function's body. No useful value is returned.

13 #includes #defines list of prototypes #include “pgm.h” main.cfct.c prn.c pgm.h Developing large programs gcc -g -ansi -pedantic-errors main.c fct.c prn.c -o pgm

14 fct.c #include "pgm.h” void fct1( int n ) { int i = 0; printf( “Hello from fct1()\n” ); for ( i = 0; i < n; ++i ) fct2(); } void fct2( void ) { printf( “Hello from fct2()\n” ); }

15 main.c #include "pgm.h" int main( void ) { char ans = 0; int i = 0, n = N; printf( “%s”, “This program does not do very much.\n” “Do you want more information? ”); scanf( “ %c”, &ans ); if ( ans == ‘y’ || ans == ‘Y’ ) prn_info( “pgm” ); for ( i = 0; i < n; ++i ) fct1( i ); printf( “Bye!\n” ); return 0; }

16 pgm.h #include #define N 3 void fct1(int k); void fct2(void); void prn_info(char *);

17 prn.c #include "pgm.h" void prn_info( char *pgm_name ) { printf( “Usage: %s\n\n”, pgm_name ); printf( “%s\n”, “This program illustrates how one can write a program\n” “in more than one file. In this example, we have a\n” “single.h file that gets included at the top of our\n” “three.c files. Thus the.h file acts as the \“glue\”\n” “that binds the program together.\n\n” “Note that the functions fct1() and fct2() when called\n” “only say \“hello.\” When writing a serious program, the\n” “programmer sometimes does this in a first working\n” “version of the code.\n” ); }

18 Assertions #include int f( int a, int b ); int g( int c ); int main( void ) { int a = 0, b = 0, c = 0;.... scanf( “%d%d”, &a, &b );..... c = f( a,b ); assert( c > 0 );..... } an assertion: used to enforce certain logical conditions

19 Assertions int f( int a, int b ) {..... assert( a == 1 || a == -1 ); assert( b >= 7 && b <== 11 ); } The assertion makes sure that the statement evaluates to true

20 Scope Rules { int a = 1, b = 2, c = 3; printf( “%3d%3d%3d\n”, a, b, c ); { int b = 4; float c = 5.0; printf( “%3d%3d%5.1f\n”, a, b, c ); a = b; { int c; c = b; printf( “%3d%3d%3d\n”, a, b, c ); } printf( “%3d%3d%5.1f\n”, a, b, c ); } printf( “%3d%3d%3d\n”, a, b, c ); } What is the output of this code?

21 Scope Rules { int a = 1, b = 2, c = 3; printf( “%3d%3d%3d\n”, a, b, c ); { int b = 4; float c = 5.0; printf( “%3d%3d%5.1f\n”, a, b, c ); a = b; { int c; c = b; printf( “%3d%3d%3d\n”, a, b, c ); } printf( “%3d%3d%5.1f\n”, a, b, c ); } printf( “%3d%3d%3d\n”, a, b, c ); }