A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-3).

Similar documents
printf( Please enter another number: ); scanf( %d, &num2);

A PROGRAM IS A SEQUENCE of instructions that a computer can execute to

1 Getting used to Python

Running a C program Compilation Python and C Variables and types Data and addresses Functions Performance. John Edgar 2

For instance, we can declare an array of five ints like this: int numbers[5];

CS 2505 Computer Organization I Test 1. Do not start the test until instructed to do so!

Functions in C. Lecture Topics. Lecture materials. Homework. Machine problem. Announcements. ECE 190 Lecture 16 March 9, 2011

To declare an array in C, a programmer specifies the type of the elements and the number of elements required by an array as follows

Pointer Basics. Lecture 13 COP 3014 Spring March 28, 2018

Introduction to Programming in C Department of Computer Science and Engineering. Lecture No. #13. Loops: Do - While

The name of our class will be Yo. Type that in where it says Class Name. Don t hit the OK button yet.

We do not teach programming

Lecture 05 I/O statements Printf, Scanf Simple statements, Compound statements

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, SPRING 2013

CMSC 313 COMPUTER ORGANIZATION & ASSEMBLY LANGUAGE PROGRAMMING LECTURE 13, FALL 2012

3/22/2016. Pointer Basics. What is a pointer? C Language III. CMSC 313 Sections 01, 02. pointer = memory address + type

10/20/2015. Midterm Topic Review. Pointer Basics. C Language III. CMSC 313 Sections 01, 02. Adapted from Richard Chang, CMSC 313 Spring 2013

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

Programming Studio #9 ECE 190

CS113: Lecture 5. Topics: Pointers. Pointers and Activation Records

In our first lecture on sets and set theory, we introduced a bunch of new symbols and terminology.

Programming in C++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

CSE 230 Intermediate Programming in C and C++ Functions

2/6/2018. ECE 220: Computer Systems & Programming. Function Signature Needed to Call Function. Signature Include Name and Types for Inputs and Outputs

Lecture 16. Daily Puzzle. Functions II they re back and they re not happy. If it is raining at midnight - will we have sunny weather in 72 hours?

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

CAAM 420 FALL 2012 Lecture 9. Mishael Owoyemi

CHAPTER 4 FUNCTIONS. 4.1 Introduction

Programming in C. main. Level 2. Level 2 Level 2. Level 3 Level 3

CONTENTS: What Is Programming? How a Computer Works Programming Languages Java Basics. COMP-202 Unit 1: Introduction

Some Computer Preliminaries

Slide 1 Side Effects Duration: 00:00:53 Advance mode: Auto

QUIZ Friends class Y;

COMP-202 Unit 2: Java Basics. CONTENTS: Using Expressions and Variables Types Strings Methods

CS/IT 114 Introduction to Java, Part 1 FALL 2016 CLASS 10: OCT. 6TH INSTRUCTOR: JIAYIN WANG

Intro. Scheme Basics. scm> 5 5. scm>

C++ Reference NYU Digital Electronics Lab Fall 2016

Supporting Class / C++ Lecture Notes

M.CS201 Programming language

CSCI 2132 Software Development. Lecture 17: Functions and Recursion

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

Module 07: Programming in C++

Programming in C. Pointers and Arrays

Introduction to Scientific Computing and Problem Solving

4. Java Project Design, Input Methods

Intro. Speed V Growth

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

BEGINNER PHP Table of Contents

AMCAT Procedure functions and scope Sample Questions

CS 11 C track: lecture 5

Welcome! COMP s1. Programming Fundamentals

Use of scanf. scanf("%d", &number);

Discussion 1H Notes (Week 3, April 14) TA: Brian Choi Section Webpage:

Post Experiment Interview Questions

However, in C we can group related variables together into something called a struct.

AN OVERVIEW OF C. CSE 130: Introduction to Programming in C Stony Brook University

Introduction to Computing Lecture 08: Functions (Part I)

Basic Keywords Practice Session

Slide 1 CS 170 Java Programming 1 Multidimensional Arrays Duration: 00:00:39 Advance mode: Auto

Module 10A Lecture - 20 What is a function? Why use functions Example: power (base, n)

QUIZ. What is wrong with this code that uses default arguments?

Functions. Arash Rafiey. September 26, 2017

Pointers and Memory 1

(Refer Slide Time 01:41 min)

CS125 : Introduction to Computer Science. Lecture Notes #38 and #39 Quicksort. c 2005, 2003, 2002, 2000 Jason Zych

Programming Data Structures and Algorithms Prof. Shankar Balachandran Department of Computer Science Indian Institute of Technology, Madras

Functions. (transfer of parameters, returned values, recursion, function pointers).

CS125 : Introduction to Computer Science. Lecture Notes #4 Type Checking, Input/Output, and Programming Style

Problem Solving through Programming In C Prof. Anupam Basu Department of Computer Science & Engineering Indian Institute of Technology, Kharagpur

Arduino IDE Friday, 26 October 2018

Topic 6: A Quick Intro To C

static CS106L Spring 2009 Handout #21 May 12, 2009 Introduction

CSE : Python Programming

Methods. Contents Anatomy of a Method How to design a Method Static methods Additional Reading. Anatomy of a Method

MITOCW watch?v=rvrkt-jxvko

Announcements. PS 3 is due Thursday, 10/6. Midterm Exam 1: 10/14 (Fri), 9:00am-10:53am

CSC 148 Lecture 3. Dynamic Typing, Scoping, and Namespaces. Recursion

Appendix: Common Errors

1. Describe History of C++? 2. What is Dev. C++? 3. Why Use Dev. C++ instead of C++ DOS IDE?

CSE 303: Concepts and Tools for Software Development

APS105. Modularity. C pre-defined functions 11/5/2013. Functions. Functions (and Pointers) main. Modularity. Math functions. Benefits of modularity:

EECS402 Lecture 02. Functions. Function Prototype

Scope of this lecture. Repetition For loops While loops

Semantic Analysis. Lecture 9. February 7, 2018

How to approach a computational problem

1 Dynamic Memory continued: Memory Leaks

Programming in C ++ Prof. Partha Pratim Das Department of Computer Science and Engineering Indian Institute of Technology, Kharagpur

The Stack, Free Store, and Global Namespace

Computer Programming: C++

Topic 6: A Quick Intro To C. Reading. "goto Considered Harmful" History

CSE 142/143 Unofficial Commenting Guide Eric Arendt, Alyssa Harding, Melissa Winstanley

CS113: Lecture 4. Topics: Functions. Function Activation Records

CS 106B Lecture 2: C++ Functions

Computer Programming Lecture 12 Pointers


Hacking C Code - Local Machine

1 Unit 8 'for' Loops

Functions. Lecture 6 COP 3014 Spring February 11, 2018

CS102: Standard I/O. %<flag(s)><width><precision><size>conversion-code

Opening Problem. Find the sum of integers from 1 to 10, from 20 to 30, and from 35 to 45, respectively.

Transcription:

CIT Intro to Computer Systems Lecture # (//) Functions As you probably know from your other programming courses, a key part of any modern programming language is the ability to create separate functions in your code. A function is a named piece of code that performs a specific task. Sometimes functions are called methods, procedures, or subroutines (like in LC-). As in just about every other language that you've seen, a function takes some input and produces some output. The exact definitions of input and output are things we'll talk about later. Why write functions? There are a lot of software engineering-y answers to that: it makes it easier to think about how to write your program (by solving little problems and then putting those together to solve bigger problems) it makes it easier to find a bug when something goes wrong it makes it easier to change one part of the program without having to change everything else Let's say we want to write a function that determines which of two ints is bigger. This is admittedly a pretty trivial task and may not justify having its own function, but it's okay for our purposes here. Here's how that might look in C: 0 0 int find_max(int, int); main() { int num = 0, num = 0; printf( Enter the first number: ); scanf( %d, &num); printf( Enter the second number: ); scanf( %d, &num); int max = find_max(num, num); printf( The max is %d\n, max); /* * Function to determine the maximum of two numbers. */ int find_max(int a, int b) { int bigger; if (a > b) {

0 bigger = a; bigger = b; return bigger; There are three important parts of this program related to our find_max function: On line, we have the function declaration. This is sometimes called the function header or function prototype. It tells the compiler that we're going to have a function called find_max which takes two ints as its inputs, and returns an int as its output. Just like a variable, with a function, you have to declare it before you can use it. On line, we have the function invocation. This is where we call the function. The variables num and num are the inputs, or arguments to this function call. From lines - we have the function definition. This is where the code for the function goes. Note that on line, we give names to the inputs (a and b). These are called the parameters of the function. And on line 0, we have the return statement, which sends back the value of the variable bigger. What if a function doesn't take any inputs? Or doesn't return any output? In those cases, the parameters or return type would be void. For instance, you could write a function like this: void print_hello(void) { printf( hello world!\n ); return; In this case, the return statement on line doesn't take any argument; it just returns. However, all of this is a bit redundant; after all, doesn't void just mean nothing? So you could alternatively write the code like this: print_hello() { printf( hello world!\n ); Either one is acceptable. I kind of like the second one more, but maybe that's just me... Scope How can functions share variables? In the find_max example above, why doesn't main just access the variable bigger, instead of setting max to the return value of find_max? The issue here is related to scope. The scope of a variable is where it lives, i.e. the part of the code in which it can legally be accessed.

Broadly speaking, a variable can either have: global scope, in which it can be accessed by any function in the file local scope, in which it can be accessed only in the function in which it is defined Let's see an example. Note that there is no main function here; that's okay, it's just an example: 0 int x; int one(int a, int b) { int y = + x; return a + b + y; int two (int a) { x = ; y = ; return a*; On line, we have declared x as a global variable. How do we know it's global? Because it's declared outside of any function. This means that it can be used by functions one (where it is read on line ) and two (where it is modified on line ). Recall above that we mentioned function inputs and outputs. The input not only includes the function's parameters, but also any variable to which the function has access, i.e. global variables. In this case, the global variable x is also considered input to one, since its value is read. On the other hand, the output of a function not only includes its return value, but any global variables that are changed by it. Here, the function two modifies x, which is considered part of the output; this is referred to as a side effect of the function two. Note that there is a bug in this code! And the bug is related to the scope of the variable y that is declared on line. The general rule of thumb is that the scope of a variable extends from its declaration to the closing curly brace that matches the open brace closest to the declaration (got all that?). In this case, the scope of y goes from line (its declaration) to line (the closing curly brace that matches the open brace on line ), i.e. the definition of function one. Where is the bug? On line. The compiler will complain that the variable y has not been declared, because it is out of scope there. Note that changing line to int y = ; would declare a different variable called y in function two, i.e. it would not be the same as the one used in function one.

Can a local variable have the same name as a global variable? Unfortunately, yes. I say unfortunately because this can cause a lot of confusion when reading your code. For instance: 0 int x = ; int fun(int a, int b) { int x = a + b; printf( x is %d\n, x); return a + b; In this case, we have a global variable called x declared on line, and a local variable called x declared on line. So what gets printed on line? The compiler assumes that, if you declared a local variable with the same name as a global variable, you must mean to use that one. So on line, the local variable x (which has the value a + b) will be printed. Scope can be a tricky thing, and it's best to use distinct variable names whenever possible. Keep in mind the rule about the scope being related to closing curly braces. Let's look at an example. Here's a function that's attempting to return the absolute value of the difference between two ints: 0 int diff = x y; diff = y x; Here, the scope of the variable diff is only from its declaration (line ) to the closing curly brace (line ), so clearly it's out of scope when you try to use it on lines and 0; the compiler will complain about this. So perhaps you try to do this: int diff = x y;

0 int diff = y x; Nope, still not right. First of all, the variable diff declared on line is not the same as the one declared on line. Since they have different scopes, they will be considered different by the compiler. Regardless, neither is in scope when you get to line 0. So, you try to fix it by doing this: 0 int diff = 0; int diff = x y; int diff = y x; Ah ha! This actually compiles. Now we're getting somewhere, right? Sadly, no. By declaring a variable called diff on line, you're creating a new variable and the compiler will think that's the one in which you want to store x y. So when you get to line, the diff there is not the one declared on line (which is no longer in scope), but rather is referring to the one declared on line, which is still 0. Oops. A way to think about it is that, in the example above, you've basically written this code: 0 int diff = 0; int diff = x y; int diff = y x;

Now it's clear that what's used on line is different from what's declared on lines and. Put simply, if you're declaring the same variable more than once in the same function, then you're probably doing something wrong. Of course, the correct implementation is: 0 int diff = 0; diff = x y; diff = y x; Call-by-value One last important aspect of using functions in C is to understand that, when you use a variable as an argument to a function, its value is passed. This is known as a call-by-value approach (as opposed to call-by-reference ). Here's an example: 0 int swap(int, int); main() { int a =, b = ; swap(a, b); printf( now a is %d\n, a); int swap(int x, int y) {

int temp = x; x = y; y = temp; Let's start by looking at the function swap. As you can tell, it swaps the values of x and y (so that x has the value of y when the function ends, and vice versa). So what gets printed on line? Is a? Or is it? It's still. Why? Because when swap is called, the parameter x takes on the value of a, which is. The parameter x is not an alias of a (i.e., it's not another name for a), it's a totally different variable that just so happens to have the same value of a. When we change x, though, we don't change a. So a is still when we get back to line. Why, then, is C a call-by-value language? We'll answer that next time...