Functions and Program Structure CSE 2031 Fall 2010 128 June 2016.

Slides:



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

1 Storage Duration and Scope –Local and global variables Storage classes –automatic, static, external, register Todays Material.
Subroutines – parameter passing passing data to/from a subroutine can be done through the parameters and through the return value of a function subroutine.
Copyright © 2000, Daniel W. Lewis. All Rights Reserved. CHAPTER 9 MEMORY MANAGEMENT.
Programming III SPRING 2015 School of Computer and Information Sciences Francisco R. Ortega, Ph.D. McKnight Fellow and GAANN Fellow LECTURE #3 Control.
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
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.
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.
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 Modularity In “C”. 2 General Syntax data_type function_Name (parameter list) { … return expression; // return output } Body of the function is a compound.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
1. 2 FUNCTION INLINE FUNCTION DIFFERENCE BETWEEN FUNCTION AND INLINE FUNCTION CONCLUSION 3.
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.
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.
1 CISC181 Introduction to Computer Science Dr. McCoy Lecture 19 Clicker Questions November 3, 2009.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
C++ for Engineers and Scientists Third Edition
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.
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
 2007 Pearson Education, Inc. All rights reserved C Functions.
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.
Chapter 6: User-Defined Functions
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.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
18. DECLARATIONS.
Learners Support Publications Classes and Objects.
 2007 Pearson Education, Inc. All rights reserved C Functions -Continue…-
Fundamentals of C and C++ Programming. EEL 3801 – Lotzi Bölöni Sub-Topics  Basic Program Structure  Variables - Types and Declarations  Basic Program.
CPS120: Introduction to Computer Science Functions.
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.
1 Announcements Note from admins: Edit.cshrc.solaris instead of.tcshrc Note from admins: Do not use delta.ece.
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.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
Copyright © 2006 The McGraw-Hill Companies, Inc. Basic Terminology Value-returning functions: –known as “non-void functions/methods” in C/C++/Java –called.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
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.
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.
Procedure Activations Programming Language. Exploration Name ocurrenceDeclarationLocationValue scopeactivationstate a.From names to their declarations.
Revisiting building. Preprocessing + Compiling 2 Creates an object file for each code file (.c ->.o) Each.o file contains code of the functions and structs.
Functions and Program Structure Chapter 4. Introduction Functions break large computing tasks into smaller ones Appropriate functions hide details of.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 10 Java Fundamentals Objects/ClassesMethods.
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.
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
Functions and Program Structure
Functions and Program Structure
Functions.
Presentation transcript:

Functions and Program Structure CSE 2031 Fall June 2016

Function Basics (4.1) Functions  Brake large computing tasks into smaller: During the design stage try to separate small tasks that may be implemented as single function.  Can be reused Scope  Where the name can be used/visible? 2

Definition and Declaration Declaration returned_type function_name ( list_of_arguments ) ; Definition returned_type function_name ( list_of_arguments ) { declarations and statements } Return statement return expresssion ; 3

return Statement (4.2) Functions use return statement to return the result to the caller. return expression; Functions can return arbitrary type: void, int, double, pointer (to the variable or function), etc. Inconsistent expressions will be cast to the returned type of the function. 4

External Variables (4.3) Internal variables  Defined inside of the function body and exists only when the function is executed. External objects  External variables and function are defined outside of any function.  External variables may be used as a tool to communicate between functions. 5

External Variables (cont.) Problems with external variables  Everyone can access the variable (like public variables in Java).  Low level of control.  Too many externals leads to bad program structure with too many data connections between functions (problem with modularity and reusing). Bottom line:  Avoid external variables whenever possible! 6

Scope (4.4) Scope is a part of the program within which a declared name can be used. Questions of interest:  How to write declarations so that variables are properly  declared during compilation?  How are declarations arranged so that all the pieces will be properly connected when program is loaded?  How are declarations organized so there is only one copy?  How external variables are initialized (so that all of them are initialize once)? 7

extern Declaration In order to use a variable in another file or before its definition. file1.c extern int size ; extern char buff[ ] ; file2.c int size = SIZE ; char buff[SIZE] ; 8

Declaration vs. Definition Declaration: announces the properties of a variable (type). file 1.c extern int sp; extern double val[ ]; Definition = Declaration + Storage to be set aside. file2.c int sp = 0; double val[MAXVAL]; 9

Static Variables (4.6) static declaration restricts (hide) the visibility (scope) of a variable or a function. Static external variables: visible only in the source file in which they are defined. Routines in Comp.c and Main.c cannot access buf[] or bufp. Those variable names can be used in Comp.c and Main.c for other variables without any conflict since they are not visible outside io.c. /* File io.c */ #include static char buf[BUFSIZE]; static int bufp = 0; int getch(void) {... } void ungetch(int c) {... } /* end of file io.c */ 10

Project Comp.oMain.oio.o io.h io.c Main.cCommon.hComp.c Project1: Comp.o main.o io.o cc Comp.o main.o io.o –o Project Comp.o : Comp.c Common.h cc –c Comp.c Main.o: Main.c Common.c io.h cc –c Main.c io.o: io.h io.c cc –c io.c

Static Variables (cont.) Static function: its name is invisible outside of the file in which it is declared. Note: function names are normally global. Static internal variable:  visible only inside the function in which it is defined.  remains in existence (not coming and going each time the function is called).  provide private, permanent storage within a single function. static int power (int base, int n) {... } int getline(char s[]) { static int counter; int next;... } 12

Register Variables (4.7) register declaration advises the compiler that the variable will be heavily used. The register variable will be placed in machine registers  smaller, faster program. Compilers are free to ignore the advice. Examples: register int i; register char c; my_func( register long x, register unsigned y ) 13

Register Variables (cont.) Restrictions due to underlying hardware: Only a few registers available. Only certain types are allowed.  Excess/disallowed declarations are treated as normal variables. Not possible to take address of a register var. 14

Block Structure (4.8) Block: delimited by { and } if (n > 0) { int i; /* declare a new i */ for (i = 0; i < n; i++)... } i is initialized each time the block is entered. A static variable is initialized only the first time the block is entered. 15

Block Structure (cont.) int x; int y;... f(double x) { double y; } The above works, but avoid that programming style! 16

Initialization (4.9) Explicit initialization External and static vars: constant expressions Automatic and register vars: any expressions (involving pre-defined values or function calls) int x = 1; char squota = '\''; long day = 1000L * 60L * 60L * 24L; /* milliseconds/day */ int binsearch(int x, int v[], int n) { int low = 0; int high = n - 1; int mid;... } 17

Initialization (cont.) No explicit initialization External and static vars: initialized to 0. Automatic and register vars: undefined (garbage) initial values. Arrays: int days[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 }; /* array of size 12 */ int months[12] = { 100, 25, 75 }; /* the rest is 0*/ char pattern = "ould"; /* same as below */ char pattern[] = { 'o', 'u', 'l', 'd', '\0' }; 18

Recursion (4.10) In C, a function may call itself either directly or indirectly. #include /* print n in decimal */ void printd(int n) { if (n < 0) { putchar('-'); n = -n; } if (n / 10) printd(n / 10); putchar(n % 10 + '0'); } 19

Recursion (cont.) Advantages:  More compact code  Easier to write and understand Disadvantage: more overhead for recursive function calls  Stack  Parameter saving and returning 20

Macro Substitution (4.11.2) #define name replacement text  subsequent occurrences of the token name will be replaced by the replacement text. Examples: #define max(A, B) ((A) > (B) ? (A) : (B)) x = max(p+q, r+s); /* x = ((p+q) > (r+s) ? (p+q) : (r+s)); */ i =1; j = 10; y = max(i++, j++); /* final values of i and j ?*/ #define square(x) x * x /* what’s wrong? */ z = square(y + 1); 21

Next time... Big lab test 1 (10% of overall grade) 22