0 Chap. 4 Functions and Program Structure 4.1 Basics of Functions 4.2 Functions Returning Non-integers 4.3 External Variables 4.4 Scope Rules 4.5 Header.

Slides:



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

Introduction to C Programming
1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
Modular Programming With Functions
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
Expressions and Statements. 2 Contents Side effects: expressions and statements Expression notations Expression evaluation orders Conditional statements.
Chapter 7: User-Defined Functions II
Kernighan/Ritchie: Kelley/Pohl:
Chapter 5 C Functions The best way to develop and maintain a large program is to divide it into several smaller program modules, each of which is more.
C Lecture Notes 1 Program Control (Cont...). C Lecture Notes 2 4.8The do / while Repetition Structure The do / while repetition structure –Similar to.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
FunctionsFunctions Systems Programming. Systems Programming: Functions 2 Functions   Simple Function Example   Function Prototype and Declaration.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
0 4.2 Functions Returning Non-integers The return statement is the mechanism for returning a value : return expression; Remark : The expression will be.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
1 Run time vs. Compile time The compiler must generate code to handle issues that arise at run time Representation of various data types Procedure linkage.
Testing a program Remove syntax and link errors: Look at compiler comments where errors occurred and check program around these lines Run time errors:
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library Functions.
Storage & Linkage: Effects on Scope Rudra Dutta CSC Spring 2007, Section 001.
Storage Classes.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
1 4.1 Basics of Functions + Control Flow Diagram of a Function Call 4.2 Functions Returning Non-integers + Prototype Function 4.3 External Variables 4.4.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
Chapter 4 Functions and Program Structure Ku-Yaw Chang Assistant Professor, Department of Computer Science and Information Engineering.
chap13 Chapter 13 Programming in the Large.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
1 4.1 Basics of Functions 4.2 Functions Returning Non-integers + Function Prototype 4.3 External Variables 4.4 Scope Rules 4.6 Static Variables + Scope.
1 Homework / Exam Finish up K&R Chapters 3 & 4 Starting K&R Chapter 5 Next Class HW4 due next class Go over HW3 solutions.
Homework K&R chapter 4. HW3: ASCII Hex to Integer int axtoi (char s[ ]) { int i, n, flag; n = 0; flag = 1; for ( i = 0; flag; i++) /* for (i = 0; ; i++)
0 4.3 First Large Coding Example: calculator (kr76-79): Example of a Stack Machine Description of the problem and approach Pseudo code Flat implementation.
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
Engineering Computing I Chapter 4 Functions and Program Structure.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
0 4.1 Basics of Functions + Execution Diagram + make 4.2 Functions Returning Non-integers + Prototype Function 4.3 External Variables 4.4 Scope Rules 4.5.
Exam / Homework Exam 1 Starting K&R chapter 4 tonight
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Reverse Polish Calculator Reverse Polish Notation 연산자가 피연산자의 뒤에 온다. 예 ) (1 – 2) * (4 + 5)  1 2 – * * 수식에서 괄호가 요구되지 않는다. ( 수식이 애매하지 않다 )
Lecture 10: Modular Programming (functions) B Burlingame 13 April 2015.
Starting Out with C++ Early Objects ~~ 7 th Edition by Tony Gaddis, Judy Walters, Godfrey Muganda Modified for CMPS 1044 Midwestern State University 6-1.
Programming Language  C Functions and Program Structure 主講人:虞台文.
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.
0 First Large Example: A Calculator (kr76-79) – Example of a Stack Machine (SM) AST ([extended] Abstract Syntax Tree) : a representation of C expressions.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
+ Storage Classes and Linkage. + Introduction Scope describe the region or regions of a program that can access and identifier Variables can be shared.
Statements / Blocks, Section 3.1 An expression becomes a statement when it is followed by a semicolon x = 0; Braces are used to group declarations and.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
0 4.1 Basics of Functions + Function Call Diagram + make 4.2 Functions Returning Non-integers + Prototype Function 4.3 External Variables 4.4 Scope Rules.
Dale Roberts Department of Computer and Information Science, School of Science, IUPUI Dale Roberts, Lecturer Computer Science, IUPUI
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
D. GotsevaPL - Lectures1 Programming Languages Lectures Assoc. Prof. PhD Daniela Gotseva
Functions and Program Structure CSE 2031 Fall June 2016.
Information and Computer Sciences University of Hawaii, Manoa
Course Contents KIIT UNIVERSITY Sr # Major and Detailed Coverage Area
C Functions -Continue…-.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
Programmazione I a.a. 2017/2018.
Stack Data Structure, Reverse Polish Notation, Homework 7
Chapter 5 - Functions Outline 5.1 Introduction
Functions and Modular Programming
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
Functions and Modular Programming
Register Variables Declaring a variable as a "register" variable is an advisory to the compiler to keep the normal location of the variable in a register,
Functions and Modular Programming
Functions and Program Structure
Homework Finish up K&R Chapters 3 & 4
Functions and Program Structure
Homework K&R chapter 4.
INTRODUCTION TO C.
Presentation transcript:

0 Chap. 4 Functions and Program Structure 4.1 Basics of Functions 4.2 Functions Returning Non-integers 4.3 External Variables 4.4 Scope Rules 4.5 Header Files 4.6 Static Variables 4.7 Register Variables 4.8 Block Structure 4.9 Initialization 4.10 Recursion 4.11 The C Preprocessor File Inclusion Macro Substitution Conditional Inclusion Session April 2003

1 4.1 Basics of Functions (1/4) Each Function has the form : return-type function-name (argument declarations) { declarations and statements } Various part may be absent; a minimal function is : dummy () {} A program is just a set of definitions of variables and functions Communication between functions : –by arguments –value returned by a function –external variables

2 4.1 Basics of Functions (2/4) : Fundamental Paradigm The Blackboard-Toolbox paradigm v1 v2 v3 Blackboard of public and private variables Toolbox of public and private functions f (x, y, z) g(x)

3 4.1 Basics of Functions (3/4) : An Example High level solution while (there’s another line) if (the line contains the pattern) print it <--- getline(line) <--- printf(line) <--- strindex(line,pattern) Graphical solution for strindex(s,t) and partial C code index i = 0, 1, … s t i index j = i, i+1, … index k = 0, 1, …k j Example : Write a program to print each line of its input that contains a particular “pattern”, i.e. a string of characters (this is a special case of the famous UNIX grep program!) for (i = 0; s[i] != ‘\0’; i++) for (j = i, k = 0; t[k] != ‘\0’ && s[j] == t[k]; j++, k++) ;

4 4.1 Basics of Functions (4/4) : A Skeleton Program #include /* for printf() */ int getline(char line[]); int strindex(char source[], char searchfor[]); char pattern[] = "ould";/* pattern to search for */ /* find all lines matching pattern KR p.69 */ main() { char line[]; while (getline(line) > 0) if (strindex(line, pattern) >= 0) printf("%s", line); } /* getline: get line into s, return length */ int getline(char s[]) {...} /* strindex: return index of t in s, -1 if none */ int strindex(char s[], char t[]) {...}

5 4.2 Functions Returning Non-integers The return statement is the mechanism for returning a value : return expression; Remark : The expression will be converted to the return type of the function if necessary.

6 4.3 External Variables A program is just a set of external objects, which are either variables or functions Functions are always external C does not allow functions to be defined inside other functions External variables are defined outside any function Internal variables to a function come into existence when the function is entered, and disappear when it is left

7 First Large Example: A Calculator Example : Write a calculator program that provides the operators +, -, *, and /. * Hint: use the reverse polish notation, i.e. an infix expression like (1-2)*(3+4) is entered as the postfix expression * Pseudo C code while (next operator or operand is not end-of-file indicator) if (number) push it else if (operator) pop operands do operation push result else if (newline) pop and print top of stack else error Skeleton Program #include … #defines … function declarations for main main() {…} external variables for push and pop void push(double f) {…} double pop(void) {…} int getop(char s[]) {…}

8 4.4 Scope Rules Definition The scope of a name is the part of the program within which the name can be used. Scope of an external variable or function lasts from the point at which it is declared to the end of the file being compiled Scope of an automatic variable (i.e. local variable of a function) is the block in which the name is declared Remarks about the definition and declaration of an external variable A declaration announces the properties of a variable (primary its type and name), whereas a definition also causes storage to be aside : double val[MAXVAL]; /* definition of an external variable */ extern double val[]; /* declaration of an external variable */ Usage: if an external variable is to be referred before it is defined, or if it is defined in a different file, then the extern declaration is mandatory

9 4.5 Header Files calc.h #define NUMBER ‘0’ int getop(char []); int getch(void); void ungetch(int); void push(double); double pop(void); #include #include "calc.h" #define MAXOP 100 main() {…} #include #include "calc.h" getop() {…} #include #define BUFSIZE ‘100’ char bufsize[BUFSIZE ]; int bufp = 0; int getch(void) {…} void ungetch(int) {…} main.c getop.c getch.c stack.c #include #include "calc.h" #define MAXVAL 100 int sp = 0; double val[MAXVAL]; void push(double) {…} double pop(void) {…}

Static Variables Definition 1.The static declaration, applied to an external variable or function, limits the scope of that object to the rest of the source file. 2.The static declaration, applied to an automatic variable (i.e. a variable defined locally to a function), promote that variable to a permanent variable. Usage static char buf[BUFSIZE]; /* buffer for ungetch */ static int bufp = 0 /* next free position in buf */ Remark 1.A static external variable is a "private global variable with permanent storage" (private and global relative to the file in which it is declared) 2.A static automatic variable is a "private local variable with permanent storage" (private and local relative to the function in which it is declared)

Register Variables Definition A register declaration advises the compiler that the variable in question will be heavely used. Usage void f(register unsigned m, register long n) { register int i;... } Remarks 1.The idea is that register variables are to be placed in machine registers (i.e. a small very rapid but very expensive memory). 2.The compilers are free to ignore the advice. 3.The register declaration can only be applied to automatic variables and to the formal parameters of a function.

Block Structure Variable can be defined in a block-structured fashion !!! Declarations of variables (including initializations) may follow the left brace that introduces any coumpound statement, not just the one that begins a function. Function cannot be defined in a block-strutured fashion !!! Functions may not be defined within other functions. Example if (n>0) { int i; /* declare a new integer i */ for (i=0; i<n; i++)... } The scope of the variable i is the "true" branch of the if; this i is unrelated to any i outside the block. Remark. Let av and sv be an automatic resp. static variable declared and initialized in a block. Then av is initialized each time the block is entered and sv only the first time. (Hint: av is a local variable without permanent storage and sv is a local variable with permanent storage!)

Initialization Fundamentals External and static variables : initialization at compile time –The initialization is done once, conceptually before the program begins execution –The initializer must be a constant expression –The value is initialized to zero in the absence of explicit initialization Automatic and register variables : initialization at run time –The initialization is done during the execution of the program, that is each time the function or block is entered –The initializer can be any expression –The value is undefined (i.e. garbage) in the absence of explicit initialization Usage int x = 1; char squote = '\''; long day = 1000L * 60L * 60L * 24L; /* milliseconds/day */ int binsearch(int x, int v[], int n) { int low=0, high=n-1, mid;... }

Recursion

The C Preprocessor