Functions and Program Structure

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.
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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
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. 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.
Chapter 7: Runtime Environment –Run time memory organization. We need to use memory to store: –code –static data (global variables) –dynamic data objects.
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.
© 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.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
18. DECLARATIONS.
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.
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.
UMass Lowell Computer Science Java and Distributed Computing Prof. Karen Daniels Fall, 2000 Lecture 9 Java Fundamentals Objects/ClassesMethods Mon.
Functions. Flow of Control Review while for do while goto break & continue switch Relational operators short circuits.
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.
Functions and Program Structure CSE 2031 Fall June 2016.
Run-Time Environments Presented By: Seema Gupta 09MCA102.
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Week 3-4 Control flow (review) Function definition Program Structures
The Three Attributes of an Identifier
Functions.
Introduction to Programming
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
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.
Functions and Structured Programming
Functions Separate Compilation
Functions.
Structures Revisited what is an aggregate construct? What aggregate constructs have we studied? what is a structure? what is the keyword to define a structure?
C-language Lecture By B.S.S.Tejesh, S.Neeraja Asst.Prof.
Programming Fundamentals Lecture #7 Functions
CS1061 C Prgramming Lecture 11: Functions
Programmazione I a.a. 2017/2018.
Instructor: Ioannis A. Vetsikas
User-Defined Functions
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
Functions and Program Structure
CSE 3302 Programming Languages
Chapter 6 - Functions Outline 5.1 Introduction
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,
Classes and Objects.
Scope Rules and Storage Types
Homework Finish up K&R Chapters 3 & 4
Submitted By : Veenu Saini Lecturer (IT)
Run Time Environments 薛智文
Functions and Program Structure
The Three Attributes of an Identifier
Functions.
Presentation transcript:

Functions and Program Structure CSE 2031 Fall 2011 24 February 2019

Function Basics (4.1) Functions Scope 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?

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

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.

External Variables (4.3) Internal variables External objects 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.

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!

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)?

extern Declaration file1.c extern int size ; extern char buff[ ] ; 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] ;

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

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. Example: 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 <stdio.h> static char buf[BUFSIZE]; static int bufp = 0; int getch(void) { ... } void ungetch(int c) { ... } /* end of file io.c */

Project1: Comp.o main.o io.o cc Comp.o main.o io.o –o Project io.h io.c Main.c Common.h Comp.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 cc -c: stop compiler after producing the object file, do not link. 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;

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 )

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.

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.

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

Initialization (4.9) Explicit initialization External and static vars: must be 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; ... }

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' };

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

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

Macro Substitution (4.11.2) #define name replacement text Examples: 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);

Final Exam December 16, 14:00-17:00.