Functions Functions, locals, parameters, and separate compilation.

Slides:



Advertisements
Similar presentations
Spring Semester 2013 Lecture 5
Advertisements

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.
1 Classes, Encapsulation, Methods and Constructors (Continued) Class definitions Instance data Encapsulation and Java modifiers Method declaration and.
Chapter 7: User-Defined Functions II
Functions ROBERT REAVES. Functions  Interface – the formal description of what a subprogram does and how we communicate with it  Encapsulation – Hiding.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Chapter 14: Overloading and Templates
COMP 14 Introduction to Programming Miguel A. Otaduy May 25, 2004.
Rossella Lau Lecture 8, DCO10105, Semester B, DCO10105 Object-Oriented Programming and Design  Lecture 8: Polymorphism & C++ pointer  Inheritance.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
The UNIVERSITY of NORTH CAROLINA at CHAPEL HILL Adrian Ilie COMP 14 Introduction to Programming Adrian Ilie July 8, 2005.
Macro & Function. Function consumes more time When a function is called, the copy of the arguments are passed to the parameters in the function. After.
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:
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Call-by-Value vs. Call-by-Reference Call-by-value parameters are used for passing information from the calling function to the called function (input parameters).
Modular Programming Chapter Value and Reference Parameters t Function declaration: void computesumave(float num1, float num2, float& sum, float&
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
Modular Programming Chapter Value and Reference Parameters computeSumAve (x, y, sum, mean) ACTUALFORMAL xnum1(input) ynum2(input) sumsum(output)
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Project 1 Due Date: September 25 th Quiz 4 is due September 28 th Quiz 5 is due October2th 1.
1 CSE1301 Computer Programming Lecture 12 Functions (Part 1)
Chapter 7 Functions. Types of Functions Value returning Functions that return a value through the use of a return statement They allow statements such.
Loops (cont.). Loop Statements  while statement  do statement  for statement while ( condition ) statement; do { statement list; } while ( condition.
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.
FUNCTIONS IN C++. DEFINITION OF A FUNCTION A function is a group of statements that together perform a task. Every C++ program has at least one function,
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
Manish K Parmar PGT (CS) K V VVNagar Thursday, December 24, 2015 Lesson on USER DEFINED FUNCTION IN C++ Presented by Manish K Parmar PGT Computer Science.
1 Chapter 6 Methods. 2 Motivation Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.
C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 15: Overloading and Templates.
Chapter 3 Functions. 2 Overview u 3.2 Using C++ functions  Passing arguments  Header files & libraries u Writing C++ functions  Prototype  Definition.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
© Janice Regan, CMPT 128, Jan CMPT 128: Introduction to Computing Science for Engineering Students Functions (2)
Functions. Flow of Control Review while for do while goto break & continue switch Relational operators short circuits.
Chapter 5 Methods 1. Motivations Method : groups statements that perform a function.  Level of abstraction (black box)  Code Reuse – no need to reinvent.
Methods.
User-Defined Functions (cont’d) - Reference Parameters.
Procedure Definitions and Semantics Procedures support control abstraction in programming languages. In most programming languages, a procedure is defined.
FUNCTIONS (C) KHAERONI, M.SI. OBJECTIVE After this topic, students will be able to understand basic concept of user defined function in C++ to declare.
Memory Management.
User-Written Functions
Chapter 7 User-Defined Methods.
Chapter 7: User-Defined Functions II
Java Programming: Guided Learning with Early Objects
Suppose we want to print out the word MISSISSIPPI in big letters.
FIGURE 4-10 Function Return Statements
Functions, locals, parameters, and separate compilation
Organization of Programming Languages
Chapter 5 Functions.
Programmazione I a.a. 2017/2018.
User-Defined Functions
FIGURE 4-10 Function Return Statements
4-2 Functions in C In C, the idea of top–down design is done using functions. A C program is made of one or more functions, one and only one of which.
Group Status Project Status.
Classes, Encapsulation, Methods and Constructors (Continued)
Lecture 18 Arrays and Pointer Arithmetic
CS2011 Introduction to Programming I Methods (II)
FIGURE 4-10 Function Return Statements
Chapter 6 Methods.
Simulating Reference Parameters in C
BBIT 212/ CISY 111 Object Oriented Programming (OOP)
Chapter 7: User-Defined Functions II
Introduction to Computer Science
FIGURE 4-10 Function Return Statements
Functions.
Chapter 6: Methods CS1: Java Programming Colorado State University
Presentation transcript:

Functions Functions, locals, parameters, and separate compilation

What is a Function? A function is a named block of code – Type: the type of the return value it computes – Input: parameters that are passed to the function – Output: its return value computed based on input parameters and maybe other stuff – Local variables: variables declared inside the function block

Typical Function int max(int a, int b) { int maxval; if (a > b) maxval = a; else maxval = b; return maxval; } type name input local variable output code block {

Exercise 1 Write the max function as given Use forward declaration for max() Write a similar min function Write a little main function to  Declare two ints  Ask for user input to set their values  Call max and min  Print out the inputs, then their max and min (with appropriate indications) Compile and test your program

What is a Function? Recall the two parts of a function: Function header Function body (or definition) Recall function header: – Type: the type of the return value – Name: name of the function – Formal parameter list: the input parameters with their types

Function Signature, Body Function signature is: – Name – Formal parameter type list – This allows compiler and linker to figure out which code to invoke Function body (or definition) – Block of code, may have local vars – Has return statement for return value

What is a Function? Function generally has: – Input: parameters that are passed to the function (may be null list) – Output: its return value computed based on input parameters (if any) and maybe other stuff – Local variables: variables declared inside the function block – generally these go away on function return

How Does a Function Pass Parameters? Function names input parameters – These are “formal parameters” that may be referenced as variables inside the function – The scope of these variables is confined to the function code block When invoked, expressions are used – These are “actual parameters” – Formal parameters are “bound” to them

Another Function int sum(int a, int b) { int sum = 0; for (int i = a; i <= b; ++i) sum += i; return sum; }

Exercise 2 Write the sum function as given Write a little main function to  Declare two ints X and Y  Ask for user input to set their values  Print out the inputs, then call sum and print out the sum from X to Y inclusive Compile and test your program What could possibly go wrong? Stand up, walk around, talk about it

Analysis What could go wrong with the sum function as written? What if the actual parameter passed in as a is greater than the actual parameter passed in as b? Did you test that case? How do we fix it?

Exercise 3 Use the max and min functions from before to fix the sum function Compile and test Did you apply max and min from inside sum, or before you called sum? Which way is “safer”? Why?

Separate Compilation A way to make the development process more efficient and manageable Typically three kinds of files: – Main program file – has main() – Header file(s) – has declarations, included in main (and elsewhere) – Implementation file(s) – has function definitions

Exercise 4 Make a header file with declarations for max, min, and sum Make a main (or driver) file with only the main() function - #include your header file Make an implementation file with the function definitions only Compile impl files with -c option Compile main with impl.o files

Example $ ls mainSum.cpp minMaxSum.h minMaxSum.cpp $ g++ -c minMaxSum.cpp $ ls *.o minMaxSum.o $ g++ -c mainSum.cpp $ g++ mainSum.o minMaxSum.o $./a.out...

Analysis What is going on here? Compiler produces “relocatable object” code that has information needed for linking – What references are dangling – What references it can bind Linker can then link these.o files to make an a.out executable file

Why Bother? Exercise 5 Take your old file that had main that called max and min and make it into a driver only (no max or min function definitions in it) – just #include the header file you just made Now compile your new main with the minMaxSum.o file Test it out!

Reflection So now you are able to define and compile useful functions separately from the code that invokes them! What are some benefits of this? – Only have to recompile the files that change (directly or indirectly) – Can have team members each work on their own file(s)

Hey, I Know a Better Way... Look back at the sum function Is there a better way to compute the same value? – Euler did this as a schoolchild – sum(a, b) = count x average = (b – a + 1) * (a + b) / 2

Exercise 6 Take your old impl file with the definition of sum() in it and change it to compute the sum the Euler way Now compile your new impl with the -c option Now link your old main.cpp to the new relocatable object file Test it out!

Reflection The header did not change The interface to the functions did not change The result of the computation did not change So we did not need to recompile the driver or change the header!

More Reflection However, even though only the sum() function changed, we had to recompile the whole impl file with max() and min() in it What if each of these took 10 minutes to compile? Better still to separate out each function in its own impl file and compile each separately

Exercise 7 Split the impl file into three files – one each for sum, max, and min Note that you will need the header file (at least in sum.cpp) Now compile them with the -c option Now link your old main.cpp to the new relocatable object files Test it out!

(Same) Reflection The header did not change The interface to the functions did not change The result of the computation did not change So we did not need to recompile the driver or change the header!

How Does a Function Pass Parameters? There are several ways a function may pass parameters – By value – By reference – By copy-in-copy-out – By pointer (sometimes also called reference) – By name

Call-by-Value This is the most common way to pass parameters Space for the type declared in the formal parameter list is allocated on the stack The value of the expression used at invocation is stored into that place on the stack

Call By Value void swap(int a, int b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Questions?

Call By Value void swap(int a, int b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Call By Reference void swap(int* ints, int i_1, int i_2) { int temp = ints[i_1]; ints[i_1] = ints[i_2]; ints[i_2] = temp; } public void main() { int[] ints = {1, 2, 3, 4}; swap(ints, 0, 3); } ints 1234

Function Calls In C++, each function may specify the manner by which its parameters are received. – The type declaration of the parameter determines whether the data is passed “by value” or “by reference.” Value types are said to be passed “call by value”. On the other hand, reference types are said to be passed “call by reference.”

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Call By Reference (2) void swap(int &a, int &b) { int temp = a; a = b; b = temp; } void main() { int a = 2; int b = 3; swap(a, b); }

Questions?