Subprograms Subroutines Procedures Functions Methods

Total Page:16

File Type:pdf, Size:1020Kb

Subprograms Subroutines Procedures Functions Methods Subprograms Subroutines 17/05/2017 Procedures Functions Methods An introduction DFR -- PL Subprograms 1 What is a subprogram? • A “code package” with a name, … • … and possibly parameters … • … and a type (functions) 17/05/2017 Inspired by the idea of a mathematical function BUT mathematical functions have only IN PARAMETERS SUBPROGRAMS may have IN, OUT & IN‐OUT parameters (ADA) DFR -- PL Subprograms Code abstractions – reusable, lead to more abstract design Modules and interfaces 2 Terminology & Ideas • Between different programming languages, the terminology is mixed • E.g. Lisp calls these “procedures” BUT they return a value • E.g. OO calls these “methods” 17/05/2017 • E.g. C calls them functions but allows a void type procedure • Subprograms introduce the concept of scope since they define a new “environment” • The scope of a name is the environment or environments in which the name is visible or accessible DFR -- PL Subprograms • This in turn leads to “name hiding” –when a name in a subroutine hides another object with the same name in an outer environment 3 • local and non‐local environments Parameters • Subprograms may have parameters • FORMAL PARAMETER IDENTIFIER 17/05/2017 • ACTUAL PARAMETER EXPRESSION • Examples 2 literal value 2+2 literal expression DFR -- PL Subprograms The actual parameters aidentifier are the ARGUMENTS to the subprogram f(x) function call a + f(x) * 2 expression 4 Parameters Parameter passing semantics also use mixed terminology! Call-by IN OUT IN-OUT Pass-by 17/05/2017 Value Reference Return DFR -- PL Subprograms Value‐ 5 return Side effects • A SIDE EFFECT is when a data object outside the scope of the subroutine is changed (either by choice or accident) • Mathematical functions do not have side effects (pure) • Often programming subroutines do allow side effects 17/05/2017 • More efficient than copying large structures or arrays • Input / Output is a side effect • The parser ‐ reader() has no parameters but has a result • Program text buffer • Opening a file for read / write DFR -- PL Subprograms • The use of side effects should be “by choice” 6 Side effects & Parameters • OUT and IN‐OUT parameters have side effects • Call‐by reference and call‐by value‐return have side effects • HOWEVER • The point in time at which these side effects happen should also 17/05/2017 be considered • During the execution of the subroutine reference • On exit from the subroutine return • Call‐by value is the “cleanest” parameter passing method DFR -- PL Subprograms • No side effects • Conscious use of side effects is required i.e. by choice 7 Subroutines revisited • Functions may have 2 parts • The function declaration prototype, interface # & type of parameters • The function implementation return type 17/05/2017 • Functions (methods) may be declaration • Private • Public implementation • A module interface is often DFR -- PL Subprograms a collection of function prototypes e.g. the C .h files (public functions) 8 Procedures vs functions • Procedures • Design issues • parameterised code sequence • parameter passing methods ? • access to data objects • type checking actual/formal ? • direct to non‐local • local variables static/dynamic? • via parameters (in, out, in/out) • s/progs as parameters ‐ what is 17/05/2017 the referencing environment ? • Functions (user defined ops) • nesting of s/prog definitions ? • model ‐ math functions • s/prog overloading ? • fn: T1 x T2 x … x Tn => TF • generic s/progs ? • may appear in expressions • support for closures? • returns value • separate / independent compilation available? DFR - - PL Flow of Control 9 Subroutines – in summary • Subroutines have led to a “field of ideas” over time • The terminology may be “mixed” and perhaps confusing • A “code package” with a name… • …and possibly a return type… 17/05/2017 • …and possibly parameters… • Which may be IN, OUT, IN‐OUT • And have different call‐by / pass‐by semantics • value, reference, return, value‐return • Side effects which may take place during execution or on exit DFR -- PL Subprograms • Introduces the idea of scope and environments • local & non‐local environments • non‐local may have static / dynamic semantics 10 • Subroutines may have a declaration and an implementation part 17/05/2017 Subroutines & run‐time An Introduction DFR -- PL Subprograms 11 Subprograms – call subprog(a, b, c); • Process abstraction • Access to data objects • characteristics • direct to non‐local • single entry point • via actual parameters • control is transferred • positional parameters 17/05/2017 • control returned at end • keyword parameters (name) • subprogram definition • Ada & Fortran 90 • heading (prototype) • may be mixed !!! • name & type • default parameter values • formal parameter list • C++, Ada, Fortran 90 • subprogram call / return • actual parameters must match the formals in both • transfer of control number & type (usually) DFR - - PL Flow of Control 12 Subprograms • Subprogram call Code AR • parameter passing mechanism • allocation of local DOs data 17/05/2017 (data objects) • execution status of calling (sub)program unit data • transfer of control to subprogram • execute the subprogram • Fortran 77 ‐ static DFR -- PL Subprograms • transfer of control from • Algol family –dynamic subprogram • return value(s) (if any) • Algol 1960 –the stack • (run‐time stack) 13 General Model: Activation Record Static • Activation Record (AR) issues static DOs / code • static link: static scope • dynamic link: calling env Stack • format fixed at compile time 17/05/2017 dynamic local DOs • size may vary at run time • standard implementation ‐ run time stack Unallocated • why? ‐ call and return memory semantics (path within tree) & Heap reuses space in the stack • DFR -- PL Subprograms user allocated recursion ‐ several AR instances • dynamic DOs DO = data object 14 Activation Records • Fortran 77 (static) • Algol family (dynamic) Function value Function value Parameters Parameters 17/05/2017 Local DOs Local DOs Return address Static link Dynamic link • format known at compile time DFR -- PL Subprograms (DO = data object) Return address 15 17/05/2017 Subroutines & environments An Introduction DFR -- PL Subprograms 16 Referencing Environments • formal parameter semantic static modes: in, out, in‐out NLE stack • Parameter passing methods LE • pass by value (in) • pass by result (out) 17/05/2017 heap • pass by value‐result (in‐out) heap • pass by reference (in‐out) • (pass by is also called call by) SF caller (actual) callee (formal) SF a x b y SF DFR - - PL Flow of Control c z static = links = dynamic SF = stack frame 17 Activation Records: static & stack memory prog xyz; p: real; • Activation Record Instances (ARI) static + stack memory proc A(x: int): y: bool; • run time stack proc C(q: bool); {(*3*) … } { … (*2*) C(y); … } (*A*) ARI C 17/05/2017 proc B(r: real); s,t: int; ARI A ARI A { … (*1*) ... A(s); … } (*B*) { … B(p); …} (*main*) ARI B ARI B ARI B ARI ARI ARI xyz B A C xyz xyz xyz DFR -- PL Subprograms xyz data objects static A, B, C data objects stack (*1*) (*2*) (*3*) 18 Local & Non‐local References Static links dynamic x, y, z A uses x, y, z A x B uses x, y, z B x, y C uses x, y, z 17/05/2017 C x symbol table x, y, z x, z C uses x, z B uses x, z A B C x DFR -- PL Subprograms x A uses x, z z x, z Dynamic: C(C.x,P.y,P.z), B(B.x,B.y,P.z), A(A.x,B.y,P.z) 19 Dynamic: A(P.x,A.z), B(B.z,A.z), C(C.x,A.z) P=program Local & non‐local references • Static or Lexical refs A • Lexically (textual) B enclosing environment C 17/05/2017 symbol table • Dynamic refs • The environment of the callee A B C • i.e. trace back the call sequence DFR -- PL Subprograms 20 Modules and separate compilation 17/05/2017 DFR -- PL Subprograms Modules – export and import functions Functions are private or public Collection of modules (e.g. C parser / OO) The function prototype is exported i.e. an interface 21 Parameter passing 17/05/2017 semantics revisited DFR -- PL Subprograms 22 Parameter Passing Mechanisms • Pass by value • Pass by value‐result • value of actual parameter is • combination of pass by value copied to formal parameter and by result (see above) • issues • Pass by reference • expensive for large structures 17/05/2017 (e.g. arrays) • access path (reference i.e. • extra storage required address) to actual parameter • Pass by result is copied to formal parameter (aliasing !) • value of formal parameter is copied to actual (at end of • issues subprogram execution) • more efficient than • issues value/result • as pass by value • slower (indirect) access DFR - - PL Flow of Control 23 Parameter Passing Mechanisms Some problems • By value • pass by result • On entry: fp = value(ap) • During : fp ap ‐ no effect call fn(a, a) / formal fn(x,y) • On exit: fp ap ‐ no effect • By result • whichever of x, y is last 17/05/2017 assigned decides the result • On entry: ‐‐‐ • During : fp ap ‐ no effect • a= x; a = y || a = y; a = x ??? • On exit: ap = value(fp) • pass by reference • By value result • On entry: fp = value(ap) call fn(&a, &a) / formal fn(*x,*y) • During : fp ap ‐ no effect • means x, y are aliases • On exit: ap = value(fp) • a= last assignment to *x || *y • By reference DFR - - PL Flow of Control no control over in / out semantics • On entry: fp = address(ap) • During : fp ap ‐ can change • On exit: ‐‐‐ 24 Subprograms: Summary • Call semantics • Parameter passing • stack + ARIs • By value (in) • static links ‐ static scope • By result (out) (lexical scope) • By value‐result (in‐out) • dynamic links • By reference (in‐out) 17/05/2017 • call sequence • dynamic scope • Formal parameters are IDs • References to data objects • Actual parameters are • local (within the ARI) expressions • non‐local DFR -- PL Subprograms 25.
Recommended publications
  • 1. Introduction to Structured Programming 2. Functions
    UNIT -3Syllabus: Introduction to structured programming, Functions – basics, user defined functions, inter functions communication, Standard functions, Storage classes- auto, register, static, extern,scope rules, arrays to functions, recursive functions, example C programs. String – Basic concepts, String Input / Output functions, arrays of strings, string handling functions, strings to functions, C programming examples. 1. Introduction to structured programming Software engineering is a discipline that is concerned with the construction of robust and reliable computer programs. Just as civil engineers use tried and tested methods for the construction of buildings, software engineers use accepted methods for analyzing a problem to be solved, a blueprint or plan for the design of the solution and a construction method that minimizes the risk of error. The structured programming approach to program design was based on the following method. i. To solve a large problem, break the problem into several pieces and work on each piece separately. ii. To solve each piece, treat it as a new problem that can itself be broken down into smaller problems; iii. Repeat the process with each new piece until each can be solved directly, without further decomposition. 2. Functions - Basics In programming, a function is a segment that groups code to perform a specific task. A C program has at least one function main().Without main() function, there is technically no C program. Types of C functions There are two types of functions in C programming: 1. Library functions 2. User defined functions 1 Library functions Library functions are the in-built function in C programming system. For example: main() - The execution of every C program starts form this main() function.
    [Show full text]
  • 3. Fortran Program Interfaces
    Chapter 3 3. Fortran Program Interfaces Sometimes it is necessary to create a program that combines modules written in Fortran and another language. For example, • In a Fortran program, you need access to a facility that is only available as a C function, such as a member of a graphics library. • In a program in another language, you need access to a computation that has been implemented as a Fortran subprogram, for example one of the many well-tested, efficient routines in the BLAS library. Tip: Fortran subroutines and functions that give access to the IRIX system functions and other IRIX facilities already exist, and are documented in Chapter 4 of this manual. This chapter focuses on the interface between Fortran and the most common other language, C. However other language can be called, for example C++. Note: You should be aware that all compilers for a given version of IRIX use identical standard conventions for passing parameters in generated code. These conventions are documented at the machine instruction level in the MIPSpro Assembly Language Programmer's Guide, which also details the differences in the conventions used in different releases. How Fortran Treats Subprogram Names The Fortran compiler normally changes the names of subprograms and named common blocks while it translates the source file. When these names appear in the object file for reference by other modules, they are normally changed in two ways: • converted to all lowercase letters • extended with a final underscore ( _ ) character 27 Chapter 3: Fortran Program Interfaces Normally the following declarations SUBROUTINE MATRIX function MixedCase() COMMON /CBLK/a,b,c produce the identifiersmatrix_, mixedcase_, and cblk_ (all lowercase with appended underscore) in the generated object file.
    [Show full text]
  • Explain Function Declaration Prototype and Definition
    Explain Function Declaration Prototype And Definition ligatedreprobated,Sidearm feminizes and but road-hoggish Weylin vengefully. phonemic Roderich nose-dived never reckons her acetones. his carat! Unfabled Dubitative Dewey and ill-equippedclangour, his Jerzy stringer See an example of passing control passes to function declaration and definition containing its prototype Once which is declared in definition precedes its definition of declaring a body of. Check out to explain basic elements must be explained below. They gain in this browser for types to carry out into parts of functions return statement of your pdf request that same things within your program? Arguments and definitions are explained below for this causes an operator. What it into two. In definition and declare a great; control is declared in this parameter names as declaring extern are explained in expressions and ms student at runtime error. Classes and definition was tested in a, and never executed but it will be called formal parameters are expanded at later. There are definitions to prototype definition tells the value method of an example are a function based on the warnings have had been declared. Please enter valid prototype definition looks a function definitions affects compilation. In this method is fixed words, but unlike references or rethrow errors or constants stand out its argument is only if more code by subclasses. How do is the variable of the three basic behavior of variable num to explain actual values of yours i desired. Also when a function num_multiplication function and definition example. By value of the definitions are explained in the nested function, the program passes to.
    [Show full text]
  • DWARF Debugging Information Format
    DWARF Debugging Information Format UNIX International Programming Languages SIG Revision: 1.1.0 (October 6, 1992) Published by: UNIX International Waterview Corporate Center 20 Waterview Boulevard Parsippany, NJ 07054 for further information, contact: Vice President of Marketing Phone: +1 201-263-8400 Fax: +1 201-263-8401 International Offices: UNIX International UNIX International UNIX International UNIX International Asian/Pacific Office Australian Office European Office Pacific Basin Office Shinei Bldg. 1F 22/74 - 76 Monarch St. 25, Avenue de Beaulieu Cintech II Kameido Cremorne, NSW 2090 1160 Brussels 75 Science Park Drive Koto-ku, Tokyo 136 Australia Belgium Singapore Science Park Japan Singapore 0511 Singapore Phone:(81) 3-3636-1122 Phone:(61) 2-953-7838 Phone:(32) 2-672-3700 Phone:(65) 776-0313 Fax: (81) 3-3636-1121 Fax: (61) 2 953-3542 Fax: (32) 2-672-4415 Fax: (65) 776-0421 Copyright 1992 UNIX International, Inc. Permission to use, copy, modify, and distribute this documentation for any purpose and without fee is hereby granted, provided that the above copyright notice appears in all copies and that both that copyright notice and this permission notice appear in supporting documentation, and that the name UNIX International not be used in advertising or publicity pertaining to distribution of the software without specific, written prior permission. UNIX International makes no representations about the suitability of this documentation for any purpose. It is provided "as is" without express or implied warranty. UNIX INTERNATIONAL DISCLAIMS ALL WARRANTIES WITH REGARD TO THIS DOCUMENTATION, INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL UNIX INTERNATIONAL BE LIABLE FOR ANY SPECIAL, INDIRECT OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS DOCUMENTATION.
    [Show full text]
  • CSE 341 Lecture 26
    CSE 341 Lecture 26 OOP, prototypes, and inheritance slides created by Marty Stepp http://www.cs.washington.edu/341/ How to get a "class"? • What if we want to create a class, not just one object? JavaScript, unlike Java, does NOT have classes we could emulate a constructor with a function: // Creates and returns a new Point object. function constructPoint (xValue, yValue) { // bad code return { x: xValue, y: yValue, distanceFromOrigin: function() { return Math.sqrt(this.x * this.x + this.y * this.y; } }; } > var p = constructPoint(4, -3); 2 Problems with pseudo-constructor function constructPoint (xValue, yValue) { // bad code return { x: xValue, y: yValue, distanceFromOrigin: function() { return Math.sqrt(this.x * this.x + this.y * this.y; } }; } ugly doesn't match the " new " syntax we're used to wasteful; stores a separate copy of the distanceFromOrigin method in each Point object 3 Functions as constructors // Constructs and returns a new Point object. function Point (xValue, yValue) { this .x = xValue; this .y = yValue; this .distanceFromOrigin = function() { return Math.sqrt( this .x * this .x + this .y * this .y); }; } > var p = new Point(4, -3); a constructor is just a normal function! called with new like in Java 4 Functions as constructors • in JavaScript, any function can be used as a constructor! by convention, constructors' names begin in uppercase when a function is called w/ new , it implicitly returns this function Point(x, y) { this.x = x; this.y = y; } all global "classes" ( Number , String , etc.) are functions
    [Show full text]
  • Object-Oriented Javascript
    Object-Oriented JavaScript In this chapter, you'll learn about OOP (Object-Oriented Programming) and how it relates to JavaScript. As an ASP.NET developer, you probably have some experience working with objects, and you may even be familiar with concepts such as inheritance. However, unless you're already an experienced JavaScript programmer, you probably aren't familiar with the way JavaScript objects and functions really work. This knowledge is necessary in order to understand how the Microsoft AJAX Library works, and this chapter will teach you the necessary foundations. More specifi cally, you will learn: • What encapsulation, inheritance, and polymorphism mean • How JavaScript functions work • How to use anonymous functions and closures • How to read a class diagram, and implement it using JavaScript code • How to work with JavaScript prototypes • How the execution context and scope affect the output of JavaScript functions • How to implement inheritance using closures and prototypes • What JSON is, and what a JSON structure looks like In the next chapters you'll use this theory to work effectively with the Microsoft AJAX Library. Concepts of Object-Oriented Programming Most ASP.NET developers are familiar with the fundamental OOP principles because this knowledge is important when developing for the .NET development. Similarly, to develop client-side code using the Microsoft AJAX Library, you need to be familiar with JavaScript's OOP features. Although not particularly diffi cult, understanding these features can be a bit challenging at fi rst, because JavaScript's OOP model is different than that of languages such as C#, VB.NET, C++, or Java.
    [Show full text]
  • Programming in C Computer Science
    Programming in C Computer Science Mr. P Raghavender Reddy M.Sc, M.Tech Govt. College for Men (A), Kadapa Email. Id : [email protected] Contents What is an Variable? Where Variables are Declared? What is Scope of a Variable? Types of Scopes Example Programs Learning Objects Understand the need of a variable in a program Know the different regions in a program for declaring a variable Understand the accessibility or visibility region of a variable in a program Declare the variables in different place based their use of region What is a Variable? Variable is a named memory location that have a type Before using a variable for computation, it has to be . Declare – name an object (gives a symbolic name) . Define – create an object (allocate memory) . Initialize – assign data or store data With one exception (extern variable), a variable is declared and defined at the same time. Single syntax for declaration and definition of a variable. Creation of Variable Syntax for Variable Declaration & Definition Data_Type Variable_List ; Examples: char code; int roll_no; double area, side; Syntax for Variable Initialization Variable_name = Expression ; Examples: code = ‘B’; roll_no = 532; area = side*side; Syntax for Variable Declaration, Definition & Initialization Data_Type Variable_name = Expression ; Examples: char code = ‘B’; double area, side=10.5; Creation of Variable Data Type Name of a Variable . Memory Size . An identifier . Range of Values Name of Location . Set of Operations Declaration Value code char code = ‘B’ ; B Initialization
    [Show full text]
  • Programmer Defined Functions
    CS 1023 Intro to Engineering Computing 3: Computer Programming LM4 – Programmer Defined Functions Mark Kerstetter Department of Computer Science Western Michigan University © Fall 2015 Learning about Functions What do you already know? o Built-in functions & How to Use Them h = sqrt ( a*a + b*b ) ; The parameters that are printf ( “sin(%f) = %f\n”, theta, sin( theta ) ) ; actually used when a function is called or used are known as the scanf ( “%lf %lf”, &a, &b ) ; actual parameters. You already know how to use functions! Three things you need to learn about The parameters that are named and writing your own functions used within both a function declaration programmer-defined functions and definition are known as the 1. Declare a function before you use it formal parameters. 2. How to use a function (Already doing this!) 3. Define what a function does These formal parameters act like by writing code for it placeholders and are used to receive the values or addresses of the actual Now you will learn how to parameters when the function is called write your own functions. (i.e., actually used). You need to do five things. Programmer-Defined Functions 1. Understand the Function & Sketch Solution – What is it supposed to do? 2. Name the Function 3. Decide What Kind of Data the Function Returns – Return Type o Function performs activity, but does not return a single value E.g., printf and openVatDoor (perform activities) Return type void o Function returns a single value – What type? E.g., sqrt, sin, max, firstChar (return int, double, char, etc.) Return type int, double, or char o Function returns multiple values E.g., scanf, sort, swap, reverse Return type void (changes returned through parameters) 4.
    [Show full text]
  • C and C++ Functions Variadic User-Defined Standard Predefined
    MODULE 4 FUNCTIONS Receive nothing, return nothing-receive nothing, return something- receive something, return something-receive something, return nothing And they do something. That is a function! My Training Period: hours Note: Function is one of the important topics in C and C++. Abilities ▪ Able to understand and use function. ▪ Able to create user defined functions. ▪ Able to understand Structured Programming. ▪ Able to understand and use macro. ▪ Able to appreciate the recursive function. ▪ Able to find predefined/built-in standard and non-standard functions resources. ▪ Able to understand and use predefined/built-in standard and non-standard functions. ▪ Able to understand and use the variadic functions. 4.1 Some Definition - Most computer programs that solve real-world problem are large, containing thousand to million lines of codes and developed by a team of programmers. - The best way to develop and maintain large programs is to construct them from smaller pieces or modules, each of which is more manageable than the original program. - These smaller pieces are called functions. In C++ you will be introduced to Class, another type smaller pieces construct. - The function and class are reusable. So in C / C++ programs you will encounter and use a lot of functions. There are standard (normally called library) such as maintained by ANSI C / ANSI C++, ISO/IEC C, ISO/IEC C++ and GNU’s glibc or other non-standard functions (user defined or vendors specific or implementations or platforms specific). - If you have noticed, in the previous Modules, you have been introduced with many functions, including the main(). main() itself is a function but with a program execution point.
    [Show full text]
  • Calling Non-COBOL Subprograms
    CodeBridge™ Calling Non-COBOL Subprograms ® ® Version 7.5 for UNIX and Windows This manual is a reference guide for Liant Software Corporation’s CodeBridge, a cross-language call system designed to simplify communication between RM/COBOL programs and non-COBOL subprogram libraries written in C (or C++). It is assumed that the reader is familiar with programming concepts and with the COBOL and C (or C++) languages in general. The information contained herein applies to systems running under Microsoft 32-bit Windows and UNIX-based operating systems. The information in this document is subject to change without prior notice. Liant Software Corporation assumes no responsibility for any errors that may appear in this document. Liant reserves the right to make improvements and/or changes in the products and programs described in this guide at any time without notice. Companies, names, and data used in examples herein are fictitious unless otherwise noted. No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any form or by any means, electronic, mechanical, photocopied, recorded, or otherwise, without prior written permission of Liant Software Corporation. The software described in this document is furnished to the user under a license for a specific number of uses and may be copied (with inclusion of the copyright notice) only in accordance with the terms of such license. Copyright © 1999-2002 by Liant Software Corporation. All rights reserved. Printed in the United States of America. _____________________ RM, RM/COBOL, RM/COBOL-85, Relativity, Enterprise CodeBench, RM/InfoExpress, RM/Panels, VanGui Interface Builder, CodeWatch, CodeBridge, Cobol-WOW, InstantSQL, Liant, and the Liant logo are trademarks or registered trademarks of Liant Software Corporation.
    [Show full text]
  • BTE2313 Chapter 7: Function
    For updated version, please click on http://ocw.ump.edu.my BTE2313 Chapter 7: Function by Sulastri Abdul Manap Faculty of Engineering Technology [email protected] Objectives • In this chapter, you will learn about: 1. Create and apply user defined function 2. Differentiate between standard library functions and user defined functions 3. Able to use both types of functions Introduction • A function is a complete section (block) of C++ code with a definite start point and an end point and its own set of variables. • Functions can be passed data values and they can return data. • Functions are called from other functions, like main() to perform the task. • Two types of function: 1. User defined function: The programmer writes their own function to use in the program. 2. Standard library function: Function already exist in the C++ standard libraries http://www.cplusplus.com/reference/ Introduction (cont.) • Advantages of functions: Easier to solve complex task by dividing it into several smaller parts (structured programming) Functions separate the concept (what is done) from the implementation (how it is done) Functions can be called several times in the same program, allowing the code to be reused. Three Important Questions • “What is the function supposed to do? (Who’s job is it?” ) – If a function is to read all data from a file, that function should open the file, read the data, and close the file. • “What input values does the function need to do its job?” – If your function is supposed to calculate the volume of a pond, you’d need to give it the pond dimensions.
    [Show full text]
  • 1.6 Functions
    1.6 Functions 1 Department of CSE Objectives • To understand the concept of modularization. • To know about the types of functions. • To study about formal arguments and actual arguments. • To understand the need of passing arguments to function. 2 Department of CSE Agenda • Introduction to Function • Types of C Functions • Function naming rule in C • General Form of a Function • Parameters / Arguments • Scope of a Function • Returning Value – Control from a Function • Three Main Parts of a Function • Categorization based on Arguments and Return value • Calling Functions –Two Methods • Creating user defined header files • Storage classes • Summary 3 Department of CSE Introduction to Functions Benefits of Using Functions: •It provides modularity to the program. •Easy code reusability. You just have to call the function by its name to use it. •In case of large programs with thousands of code lines, debugging and editing becomes easier if you use functions. 4 Department of CSE Credits: http://www.studytonight.com/c/types-of-function-calls.php Contd.. A function is independent: It is “completely” self-contained It can be called at any place of your code and can be ported to another program reusable - Use existing functions as building blocks for new programs Readable - more meaningful procedural abstraction - hide internal details factoring of code- divide and conquer 5 Department of CSE Contd.. A function: receives zero or more parameters, performs a specific task, and returns zero or one value A function is invoked / called by name and parameters Communication between function and invoker code is through the parameters and the return value In C, no two functions can have the same name 6 Department of CSE Types of C Functions • Library function • User defined function Library function • Library functions are the in-built function in C programming system For example: main() - -The execution of every C program printf() - prinf() is used for displaying output in C.
    [Show full text]