C/C++ Functions. Mark Redekopp

Similar documents
EE 355 Unit 2. C Review Variables & Expressions. Mark Redekopp

CSCI 104 Memory Allocation. Mark Redekopp David Kempe

Functions Overview. Functions (aka procedures, subroutines, or methods) are the unit of code decomposition and abstraction

#include <iostream> #include <algorithm> #include <cmath> using namespace std; int f1(int x, int y) { return (double)(x/y); }

Unit 6. Thinking with Functions

CS103 Unit 6 - Pointers. Mark Redekopp

CS103 Unit 6 - Pointers. Mark Redekopp

EECS402 Lecture 02. Functions. Function Prototype

CS101: Fundamentals of Computer Programming. Dr. Tejada www-bcf.usc.edu/~stejada Week 8: Dynamic Memory Allocation

Programming Language. Functions. Eng. Anis Nazer First Semester

The University Of Michigan. EECS402 Lecture 02. Andrew M. Morgan. Savitch Ch. 3-4 Functions Value and Reference Parameters.

Lab Instructor : Jean Lai

Understand Execution of a Program

1 Unit 8 'for' Loops

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

CS1150 Principles of Computer Science Methods

Unit 14. Passing Arrays & C++ Strings

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Unit 7. 'while' Loops

Chapter 7 - Notes User-Defined Functions II

Basic memory model Using functions Writing functions. Basics Prototypes Parameters Return types Functions and memory Names and namespaces

CSE 374 Programming Concepts & Tools. Hal Perkins Spring 2010

Tutorial 12 Craps Game Application: Introducing Random Number Generation and Enumerations

GE U111 Engineering Problem Solving & Computation Lecture 6 February 2, 2004

Functions. CS111 Lab Queens College, CUNY Instructor: Kent Chin

More Flow Control Functions in C++ CS 16: Solving Problems with Computers I Lecture #4

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

FORM 1 (Please put your name and section number (001/10am or 002/2pm) on the scantron!!!!) CS 161 Exam II: True (A)/False(B) (2 pts each):

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

CS1150 Principles of Computer Science Methods

CSCE 206: Structured Programming in C++

Practice test for midterm 2

Advanced Flow Control CS 16: Solving Problems with Computers I Lecture #5

C:\Temp\Templates. Download This PDF From The Web Site

CSE 303: Concepts and Tools for Software Development

Polymorphism Part 1 1

COMP 250: Java Programming I. Carlos G. Oliver, Jérôme Waldispühl January 17-18, 2018 Slides adapted from M. Blanchette

CSE 374 Programming Concepts & Tools. Hal Perkins Fall 2015 Lecture 19 Introduction to C++

1- Write a single C++ statement that: A. Calculates the sum of the two integrates 11 and 12 and outputs the sum to the consol.

More on Func*ons Command Line Arguments CS 16: Solving Problems with Computers I Lecture #8

CS2141 Software Development using C/C++ C++ Basics

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Your first C++ program

C++ For Science and Engineering Lecture 12

CS 376b Computer Vision

Exam 1. CSI 201: Computer Science 1 Fall 2018 Professors: Shaun Ramsey

Chapter 4: Subprograms Functions for Problem Solving. Mr. Dave Clausen La Cañada High School

CS 103 Lecture 3 Slides

Building on the foundation. Now that we know a little about cout cin math operators boolean operators making decisions using if statements

Functions that Return a Value. Approximate completion time Pre-lab Reading Assignment 20 min. 92

Lab 8 The Stack (LIFO) Structure

Function Call Example

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

4. C++ functions. 1. Library Function 2. User-defined Function

Solving a 2D Maze. const int WIDTH = 10; const int HEIGHT = 10;

Functions in C++ Problem-Solving Procedure With Modular Design C ++ Function Definition: a single

A506 / C201 Computer Programming II Placement Exam Sample Questions. For each of the following, choose the most appropriate answer (2pts each).

Functions. Function Prototypes. Function prototype is needed if the function call comes before the function definition in the program.

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 1/9/ Review. Here s a simple C++ program:

Chapter 2. Procedural Programming

WARM UP LESSONS BARE BASICS

Computer Programming

Ch 4. Parameters and Function Overloading

Exam 2. CSI 201: Computer Science 1 Fall 2016 Professors: Shaun Ramsey and Kyle Wilson. Question Points Score Total: 80

True or False (12 Points)

Chapter Four: Loops. Slides by Evan Gallagher. C++ for Everyone by Cay Horstmann Copyright 2012 by John Wiley & Sons. All rights reserved

Introduction to C++ 2. A Simple C++ Program. A C++ program consists of: a set of data & function definitions, and the main function (or driver)

Problem 1 Write the best title lines for the functions that are called by the following main program. Do not supply blocks for the functions.

Sample Final Exam. 1) (24 points) Show what is printed by the following segments of code (assume all appropriate header files, etc.

CS1622. Semantic Analysis. The Compiler So Far. Lecture 15 Semantic Analysis. How to build symbol tables How to use them to find

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Scientific Computing

Government Polytechnic, Muzaffarpur. Name of the Lab: OBJECT ORIENTED PROGRAMMING

Unit 3. Constants and Expressions

Welcome Back. CSCI 262 Data Structures. Hello, Let s Review. Hello, Let s Review. How to Review 8/19/ Review. Here s a simple C++ program:

Partha Sarathi Mandal

Function. Mathematical function and C+ + function. Input: arguments. Output: return value

CS102 Software Engineering Principles

Local and Global Variables

Chapter - 9 Variable Scope and Functions. Practical C++ Programming Copyright 2003 O'Reilly and Associates Page 1

Review. Modules. CS 151 Review #6. Sample Program 6.1a:

C++ for Java Programmers

CS 103 Unit 11. Linked Lists. Mark Redekopp

Scope and Parameter Passing

CS201 Some Important Definitions

Name SECTION: 12:45 2:20. True or False (12 Points)

Chapter 3. More Flow of Control. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

CS 103 Unit 13 Slides

CE221 Programming in C++ Part 2 References and Pointers, Arrays and Strings

CS103L SPRING 2018 UNIT 7: FILE I/O

LAB #8. Last Survey, I promise!!! Please fill out this really quick survey about paired programming and information about your declared major and CS.

Pointers, Dynamic Data, and Reference Types

C++ Programming for Non-C Programmers. Supplement

2 2

Attributes, Bindings, and Semantic Functions Declarations, Blocks, Scope, and the Symbol Table Name Resolution and Overloading Allocation, Lifetimes,

Memory and Pointers written by Cathy Saxton

Note 12/1/ Review of Inheritance Practice: Please write down 10 most important facts you know about inheritance...

1. a) What #include statement do you put at the top of a program that does uses cin, cout or endl?

REPETITION CONTROL STRUCTURE LOGO

Transcription:

1 C/C++ Functions Mark Redekopp

A QUICK LOOK 2

3 Functions Also called procedures or methods Collection of code that performs a task Do a task given some inputs (but we don't care how it does it a.k.a. "black box" methodology) Black-box = We know what it does, but not how it does it Attributes Has a name to identify it (e.g. avg ) Takes in 0 or more inputs (a.k.a. parameters or arguments) Performs computation Start and end of code belonging to the function are indicated by curly braces Sequence of statements Returns at most a single value (i.e. 1 value or 0 values = 'void' ) Return value is substituted for the function call

4 Execution of a Function Statements in a function are executed sequentially by default Defined once, called over and over Functions can call other functions Goes and executes that collection of code then returns to continue the current function Compute max of two integers Each call causes the program to pause the current function, go to the called function and execute its code with the given arguments then return to where the calling function left off, Return value is substituted in place of the function call #include <iostream> using namespace std; int max(int a, int b) if(a > b) return a; else return b; int main(int argc, char *argv[]) int x=6, z; 6 z = max(x,4); cout << Max is << z << endl; z = max(125, 199); cout << Max is << z << endl; return 0; 199

5 Parameter Passing x Formal parameters, a and b Type of data they expect Names that will be used internal to the function to refer to the values Actual parameters Actual values input to the function code by the caller A copy is made and given to function Actuals Formals 6 a max() 4 b 6 return val #include <iostream> using namespace std; int max(int a, int b) if(a > b) return a; else return b; int main(int argc, char *argv[]) int x=6, z; z = max(x,4); cout << Max is << z << endl; z = max(125, 199); cout << Max is << z << endl; return 0; Actuals Formals Actuals Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

6 Parameter Passing x Formal parameters, n1 and n2 Type of data they expect Names that will be used internal to the function to refer to the values Actual parameters Actual values input to the function code by the caller A copy is made and given to function Actuals 6 9 y #include <iostream> using namespace std; double avg(int n1, int n2) double sum = n1 + n2; return sum/2.0; int main(int argc, char *argv[]) copy int x=6, y = 9; double z; z = avg(x,y); cout << AVG is << z << endl; z = avg(x, 2); copy Formals n1 n2 7.5 cout << AVG is << z << endl; return 0; avg() return val Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

7 Parameter Passing x Formal parameters, n1 and n2 Type of data they expect Names that will be used internal to the function to refer to the values Actual parameters 6 Actual values input to the function code by the caller A copy is made and given to function Actuals Formals 6 x #include <iostream> using namespace std; void inc(int x) x = x+1; int main(int argc, char *argv[]) int x=6; inc(x); cout << X is << x << endl; return 0; inc() x 7 Each type is a "different" shape (int = triangle, double = square, char = circle). Only a value of that type can "fit" as a parameter..

8 Program Decomposition C is a procedural language Main unit of code organization, problem decomposition, and abstraction is the function or procedure Function or procedure is a unit of code that Can be called from other locations in the program Can be passed variable inputs (a.k.a. arguments or parameters) Can return a value to the code that called it C++ is considered an object-oriented language (really just adds objected-oriented constructs to C) Main unit of organization, problem decomposition, and abstraction is an object (collection of code & associated data)

9 Exercise To decompose a program into functions, try listing the verbs or tasks that are performed to solve the problem Model a game of poker as a series of tasks/procedures Shuffle(), deal(), bet(), flop(), A database representing a social network adduser(), addfriend(), updatestatus(), etc.

10 Anatomy of a function Return type (any valid C type) void, int, double, char, etc. void means return nothing Function name Any valid identifier Input arguments inside () Act like a locally declared variable Code In Non-void functions must have 1 or more return statements First 'return' executed immediately quits function void printmenu() cout << Welcome to ABC 2.0: << endl; cout << ===================" << endl; cout << Enter an option:" << endl; cout << 1.) Start" << endl; cout << 2.) Continue" << endl; cout << 3.) End\n" << endl; bool only_2_3_factors(int num) while(num % 2 == 0)...... if(num==1) return 1; return 0; double triangle_area(double b, double h) double area; area = 0.5 * b * h; return area;

11 Function Prototypes The compiler (g++/clang++) needs to know about a function before it can handle a call to that function The compiler will scan a file from top to bottom If it encounters a call to a function before the actual function code it will complain [Compile error] Unless a prototype ( declaration ) for the function is defined earlier A prototype only needs to include data types for the parameters but not their names (ends with a ; ) Prototype is used to check that you are calling it with the correct syntax (i.e. parameter data types & return type) (like a menu @ a restaurant) X int main() double area1,area2,area3; area3 = triangle_area(5.0,3.5); double triangle_area(double b, double h) return 0.5 * b * h; Compiler encounters a call to triangle_area() before it has seen its definition (Error!) double triangle_area(double, double); int main() double area1,area2,area3; area3 = triangle_area(5.0,3.5); double triangle_area(double b, double h) return 0.5 * b * h; Compiler sees a prototype and can check the syntax of any following call and expects the definition later.

12 The Need For Prototypes How would you order the functions in the program on the left if you did NOT want to use prototypes? You can't! int main() cout << f1(5) << endl; int f1(int x) return f2(x*x); int f2(int y) if(x > 10000) return; else f1(y); int f1(int); int f2(int); int main() cout << f1(5) << endl; int f1(int x) return f2(x*x); int f2(int y) if(x > 10000) return; else f1(y);

13 Overloading: A Function's Signature What makes up a signature (uniqueness) of a function name number and type of arguments No two functions are allowed to have the same signature; the following 6 functions are unique and allowable int f1(int), int f1(double), int f1(int, double) void f1(char), double f1(), int f1(int, char) Return type does not make a function unique int f1() and double f1() are not unique and thus not allowable Two functions with the same name are said to be "overloaded" int max(int, int); double max(double, double);

14 Remove Factors Practice Websheets Exercise: cpp/functions/remove_factor Draw an ASCII square on the screen Websheets Exercise: cpp/functions/draw_square Practice overloading a function Websheets Exercise: cpp/functions/overload

FUNCTION CALL SEQUENCING 15

16 Function Call Sequencing Functions can call other functions and so on When a function is called the calling function is suspended (frozen) along with all its data and control jumps to the start of the called function When the called function returns execution resumes in the calling function Each function has its own set of variables and scope Scope refers to the visibility/accessibility of a variable from the current place of execution void print_char_10_times(char); void print_char(char); int main() char c = '*'; print_char_10_times(c); y = 5;... return 0; void print_char_10_times(char c) for(int i=0; i < 10; i++) print_char(c); return; void print_char(char c) cout << c << endl;

17 More Function Call Sequencing As one function calls another, they execute in a last-in, first-out fashion (i.e. the last one called is the first one to finish & return) Just like in the cafeteria the last plate put on the top of the stack is the first one to be pulled off (always access the top item) How does the computer actually track where to return to when a function completes // Computes rectangle area, // prints it, & returns it int print_rect_area(int, int); void print_answer(int); int main() int wid = 8, len = 5, a; a = print_rect_area(wid,len); int print_rect_area(int w, int l) int ans = w * l; print_answer(ans); return ans; void print_answer(int area) cout << Area is << area; cout << endl;

18 Memory Organization 32-bit address range (0x0 0xffffffff) Code usually sits at lower addresses Global variables/data somewhere after code Heap: Area of memory that can be allocated and deallocated during program execution (i.e. dynamically at run-time) based on the needs of the program System stack (memory for each function instance that is alive) Local variables Return link (where to return) etc. Address 0 fffffffc Code Globals Heap Stack (area for data local to a function) Memory (RAM)

19 More Function Call Sequencing Computer maintains a stack of function data and info in memory (i.e. RAM) Each time a function is called, the computer allocates memory for that function on the top of the stack and a link for where to return When a function returns that memory is deallocated and control is returned to the function now on top Address 0x0000000 Code for all functions // Computes rectangle area, // prints it, & returns it int print_rect_area(int, int); void print_answer(int); int main() int wid = 8, len = 5, a; a = print_rect_area(wid,len); int print_rect_area(int w, int l) int ans = w * l; print_answer(ans); return ans; System Memory (RAM) 0xffff ffff Data for print_answer (area) and return link to print_rect Data for print_rect (w,l,ans) and return link to main Data for main (wid,len,a) and return link to OS System stack area void print_answer(int area) cout << Area is << area; cout << endl;

LOCAL VARIABLES & SCOPE 20

21 Local Variables Any variable declared inside a function is called a local variable It lives in the stack area for that function It dies when the function returns // Computes rectangle area, // prints it, & returns it int print_rect_area(int, int); void print_answer(int); int main() int wid = 8, len = 5, a; a = print_rect_area(wid,len); Address 0x0000000 Code for all functions int print_rect_area(int w, int l) int ans = w * l; print_answer(ans); return ans; System Memory (RAM) 0xffff ffff Data for print_answer (area) and return link to print_rect Data for print_rect (w,l,ans) and return link to main Data for main (wid,len,a) and return link to OS System stack area void print_answer(int area) cout << Area is << area; cout << endl;

22 Scope Global variables live as long as the program is running Variables declared in a block are local to that block of a function of a loop, if statement, etc. Die/deallocated when the program reaches the end of the block don t try to access them intentionally or unintentionally after they are out of scope /deallocated Actual parameters act as local variables and die when the function ends When variables share the same name the closest declaration will be used by default

23 Scope Example Globals live as long as the program is running Variables declared in a block live as long as the block has not completed of a function of a loop, if statement, etc. When variables share the same name the closest declaration will be used by default #include <iostream> using namespace std; int x = 5; int main() int a, x = 8, y = 3; cout << x = << x << endl; for(int i=0; i < 10; i++) int j = 1; j = 2*i + 1; a += j; a = doit(y); cout << a= << a ; cout << y= << y << endl; cout << glob. x << ::x << endl; int doit(int x) x--; return x; Address 0 fffffffc Code Globals x = 5 Heap doit: (x= 3=>2) main: (a=, main: x=8,y=3) (a=121, (a=2, (a, ( ( x=8,y=3) i, j ) ) Memory (RAM)

PASS BY VALUE 24

25 Pass-by-Value Passing an argument to a function makes a copy of the argument It is like e-mailing an attached document You still have the original on your PC The recipient has a copy which he can modify but it will not be reflected in your version Communication is essentially one-way Caller communicates arguments to callee, but callee cannot communicate back because he is working on copies The only communication back to the caller is via a return value.

26 Pass by Value Notice that actual arguments are different memory locations/variables than the formal arguments When arguments are passed a copy of the actual argument value (e.g. 3) is placed in the formal parameter (x) The value of y cannot be changed by any other function (remember it is local) void decrement_it(int); int main() int a, y = 3; decrement_it(y); cout << y = << y << endl; return 0; void decrement_it(int y) y--; Address 0x0000000 Code for all functions System Memory (RAM) 0xffff ffff Data for decrement_it (y=3 then 2) and return link Data Data for for main main (a, (a, y=3) y=3) and return and return link link System stack area

27 Nested Call Practice Find characters in a string then use that function to find how many vowels are in a string Websheets Exercise: cpp/functions/vowels

28 Another Exercise Guessing game Number guessing game [0-19] indicate higher or lower until they guess correctly or stop after 5 unsuccessful guesses Use a function to perform one "turn" of the game and return whether the user guessed the number correctly bool guessandcheck(int secretnum); #include <iostream> #include <cstdlib> #include <ctime> int main() srand(time(0)); int secretnum = rand() % 20; // Now create a game that // lets the user try to guess // the random number in up to // 5 guesses Ch. 5, PE 16 of D.S. Malik, C++ Programming, 6 th Ed.