ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.

Slides:



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

Introduction to C Programming
Spring Semester 2013 Lecture 5
Programming C/C++ on Eclipe Trình bày : Ths HungNM C/C++ Training.
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 6: Dynamic Memory Allocation (DMA)
C++ Programming: From Problem Analysis to Program Design, Second Edition Chapter 7: User-Defined Functions II.
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.
Lesson 6 Functions Also called Methods CS 1 Lesson 6 -- John Cole1.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 2: Control Flow.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Chapter 6: Functions.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
1 COMP 2130 Introduction to Computer Systems Computing Science Thompson Rivers University.
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.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
ASP.NET Programming with C# and SQL Server First Edition Chapter 3 Using Functions, Methods, and Control Structures.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
Copyright © 2012 Pearson Education, Inc. Chapter 6: Functions.
CPS120: Introduction to Computer Science Functions.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
CPS120: Introduction to Computer Science Lecture 14 Functions.
An Object-Oriented Approach to Programming Logic and Design Chapter 3 Using Methods and Parameters.
User Defined Functions Chapter 7 2 Chapter Topics Void Functions Without Parameters Void Functions With Parameters Reference Parameters Value and Reference.
Procedural Programming Criteria: P2 Task: 1.2 Thomas Jazwinski.
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.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Structure Programming Lecture 8 Chapter 5&6 - Function – part I 12 December 2015.
FUNCTION Dong-Chul Kim BioMeCIS UTA 12/7/
CCSA 221 Programming in C CHAPTER 8 – PART 1 WORKING WITH FUNCTIONS 1.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
User Defined Methods Methods are used to divide complicated programs into manageable pieces. There are predefined methods (methods that are already provided.
Chapter Functions 6. Modular Programming 6.1 Modular Programming Modular programming: breaking a program up into smaller, manageable functions or modules.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
Functions, Scope, and The Free Store Functions Functions must be declared by a function prototype before they are invoked, return_type Function_name(type,
Functions  A Function is a self contained block of one or more statements or a sub program which is designed for a particular task is called functions.
Copyright © 2015, 2012, 2009 Pearson Education, Inc., Publishing as Addison-Wesley All rights reserved. Chapter 6: Functions.
Department of Electronic & Electrical Engineering Functions Parameters Arguments Pointers/dereference & * Scope Global/Local Storage Static/Automatic.
Functions Chapter 5. Function A set of instructions that are designed to perform specific task. A complete and independent program. It is executed by.
Functions Dr. Sajib Datta Functions A function is a self-contained unit of program code designed to accomplish a particular task. Some functions.
A First Book of ANSI C Fourth Edition
1 Chapter 8 Scope, Lifetime, and More on Functions CS185/09 - Introduction to Programming Caldwell College.
1 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
Chapter 9: Value-Returning Functions
Chapter 6: User-Defined Functions I
Chapter 7: User-Defined Functions II
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
Chapter 6: Functions Copyright © 2010 Pearson Education, Inc. Publishing as Pearson Addison-Wesley.
User-Defined Functions
Scope, Parameter Passing, Storage Specifiers
6 Chapter Functions.
Chapter 7: User-Defined Functions II
Chapter 9: Value-Returning Functions
In C Programming Language
Based on slides created by Bjarne Stroustrup & Tony Gaddis
1-6 Midterm Review.
Presentation transcript:

ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions

ספטמבר 04Copyright Meir Kalech2 C is a procedural language that is based on functions. A function is a self-contained unit of program code, designed to accomplish a particular task. Every C program starts by executing a function named main, which in turn may call other functions. A function can perform various actions and then return a value. Introduction

ספטמבר 04Copyright Meir Kalech3 We use functions for several purposes:  To save repetitions.  To make programs more modular (easier to change and maintain).  Save work by using functions that have already been written and tested in other programs.  Readability (avoid ‘ spaghetti ’ code). A function has 3 parts: 1.Declaration 2.Definition 3.Invocation Introduction - Purpose

ספטמבר 04Copyright Meir Kalech4 To call a function we invoke its name attached to parentheses (). Example: Function Invocation void main() { func1(); func2(); func1(); } func1() { perform a task } func2() { perform a task }

ספטמבר 04Copyright Meir Kalech5 Function declaration is the prototype of a function. Syntax: return_type: The type of the value that the function returns. If no return type is specified, int is the default. If the function only performs some task and has no value to return, one should specify void as the return type. Declaration return_type Function_name(parameters);

ספטמבר 04Copyright Meir Kalech6 Parameters: The parameters are local variables that are initialized with values passed to the function. A function may have no parameters. In this case the parentheses are empty. The declaration role is to prevent errors in compilation. Without the declaration, the compiler cannot recognize the invoked function characteristics. Therefore, the declaration should always be before main. Declaration

ספטמבר 04Copyright Meir Kalech7 Declaration void print_header(); Return type Function name Parameters void main() { print_header(); }

ספטמבר 04Copyright Meir Kalech8 The function body contains: Definitions of local variables which are optional but usually exist. Executable statements, which may be any statement in C. If the function returns a value, the return statement is mandatory. It may appear in a function more than once. Syntax: return (expression); The parentheses are optional. If the function returns no value (void), it can still be stopped before its end. Syntax: return; Usually the function appears below the main. Definition

ספטמבר 04Copyright Meir Kalech9 Definition void print_stars(); void main() { int x, y; scanf(“%d%d”, &x, &y); print_stars(); printf(“%d”, x+y); print_stars(); } void print_stars() { int i; for(i=0; i<5; i++) printf(“*”); printf(“\n”); } #include Includes libraries Declaration (prototype) Main function Definition (implementation) Via compilation time Via linking time

ספטמבר 04Copyright Meir Kalech10 Function invocation is enabled with parameters. The parameters are sent to the function by being placed in the parentheses. We should define, both in the prototype and in the definition, the parameter ’ s types, in the same order they are sent in the invocation. Invoking a function with inappropriate parameters causes a compilation error. Let ’ s rewrite the print_stars function, so that it will print out a varying number of whichever char is requested by the calling function. For example, print_stars(6, '$' ); will result in 6 dollar signs in a row. Parameters

ספטמבר 04Copyright Meir Kalech11 Parameters void print_stars(int num, char sign); void main() { int x, y; scanf(“%d%d”, &x, &y); print_stars(6, ’$’); printf(“%d”, x+y); print_stars(5, ’*’); } void print_stars(int num, char sign) { int i; for(i=0; i<num; i++) printf(“%c”, sign); printf(“\n”); } #include Includes libraries Declaration (prototype) Main function num=6 sign= ‘ $ ’ Definition (implementation)

ספטמבר 04Copyright Meir Kalech12 A function may return a value. The value is returned to the calling code. The returned value has: Value Type Address The returned type is written at the start of the function prototype and definition. We can exploit the returned value of the invocation by assigning it to a variable. Returning a Value

ספטמבר 04Copyright Meir Kalech13 Returning a Value void print_stars(); int sum_numbers(int x, int y); void main() { int x, y, sum; scanf(“%d%d”, &x, &y); sum = sum_numbers(x, y); print_stars(); printf(“%d”, sum); print_stars(); } void print_stars() { printf(“******”); } int sum_numbers(int x, int y) { int sum; sum = x+y; return sum; } #include temp temp is created automatically by the compiler temp=sum

ספטמבר 04Copyright Meir Kalech14 Returning a Value void print_stars(); int sum_numbers(int num1, int num2); void main() { int x, y, adding; scanf(“%d%d”, &x, &y); adding = sum_numbers(x, y); print_stars(); printf(“%d”, adding); print_stars(); } void print_stars() { printf(“******”); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } #include No compatibility is needed between parameter ’ s names or returned value ’ s name and main ’ s variables

ספטמבר 04Copyright Meir Kalech15 Returning a Value void print_stars(); int sum_numbers(int num1, int num2); void main() { int x, y; scanf(“%d%d”, &x, &y); print_stars(); printf(“%d”, sum_numbers(x, y)); print_stars(); } void print_stars() { printf(“******”); } int sum_numbers(int num1, int num2) { return num1+num2; } #include Another way to write it Print directly the returned value return directly the adding result

ספטמבר 04Copyright Meir Kalech16 The scope of a variable is the part of the program in which the variable is visible (i.e., may be accessed and used). The scope of local variable is limited to a block. For instance, we can not access x (of main) from a function. The lifetime of a variable is the time between the ‘ birth ’ of the variable in the memory and the time it ‘ dies ’. The lifetime of a local variable is only throughout the block. For instance, x (of main) is born in the beginning of the main block and dies at the end of the main block. Scope and Lifetime

ספטמבר 04Copyright Meir Kalech17 Definition: storing local variables of a function in a memory area using a stack form (LIFO: Last In, First Out). Stack pointer: pointer to the active element in the stack. The stack is prepared during compiling time. Stack Segment Local variables Return address (where to return) Returned value

ספטמבר 04Copyright Meir Kalech18 Stack Segment Example sum num2 num1 Return address Returned value adding y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } sum_number s main

ספטמבר 04Copyright Meir Kalech19 Stack Segment Example sum num2=4 num1= Returned value adding y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } sum_numbers main After arguments sending

ספטמבר 04Copyright Meir Kalech20 Stack Segment Example sum=7 num2=4 num1= Returned value adding y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } sum_numbers main After sum=num1+num2;

ספטמבר 04Copyright Meir Kalech21 Stack Segment Example sum=7 num2=4 num1= adding y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } sum_numbers main After update of returned value

ספטמבר 04Copyright Meir Kalech22 Stack Segment Example adding y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } main After freeing of local variables

ספטמבר 04Copyright Meir Kalech23 Stack Segment Example adding=7 y=4 x=3 void main() { int x=3, y=4, adding; adding = sum_numbers(x, y); } int sum_numbers(int num1, int num2) { int sum; sum = num1+num2; return sum; } main After assigning returned value to adding

ספטמבר 04Copyright Meir Kalech24 Scope: from the line it is defined up to the end of the file. Lifetime: during program execution. Initialization: if the global variable is not initialized, its default initialization is 0. Example: void func(); int glob;//0 void main() { glob = 5; printf(“%d”, glob); //5 func(); printf(“%d”, glob); //8 } void func() { glob = 8; } Global Global variables are not created in the stack segment but in the data segment (heap)

ספטמבר 04Copyright Meir Kalech25 Scope: from the line it is defined up to the end of its block. Lifetime: during program execution. Initialization: if the static variable is not initialized, its default initialization is 0. Example: void func(); void main() { int i; for(i=0; i<3; i++) func(); } void func() { static int stat; int local = 0; printf( “ %d %d\n ”, stat++, local++); } Static Static variables are not created in the stack segment but in data segment (heap) 0 address: 100 stat 0 address: 200 local

ספטמבר 04Copyright Meir Kalech26 Example state after second call. Example: void func(); void main() { int i; for(i=0; i<3; i++) func(); } void func() { static int stat; int local = 0; printf( “ %d %d\n ”, stat++, local++); } Static 1 address: 100 stat 0 address: 340 local

ספטמבר 04Copyright Meir Kalech27 Example state after third call. Example: void func(); void main() { int i; for(i=0; i<3; i++) func(); } void func() { static int stat; int local = 0; printf( “ %d %d\n ”, stat++, local++); } Static 2 address: 100 stat 0 address: 280 local

ספטמבר 04Copyright Meir Kalech28 Summary Table GlobalStaticAutomatic Local declaration outside any function in a block { } initialization unless specified otherwise, automatically initialized to 0 no automatic initialization – it should specifically be initialized after each ‘ birth ’ scope its fileits block ‘ birth ’ once, before main() each time the block is entered ‘ death ’ once, after main() ends each time the block is exited address on the data segment on the stack segment