Functions in C C Programming and Software Tools

Similar documents
Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Function Call Stack and Activation Records

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Chapter 5 C Functions

Lecture 04 FUNCTIONS AND ARRAYS

CSE 230 Intermediate Programming in C and C++ Functions

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

Programming for Engineers Functions

Arrays in C C Programming and Software Tools. N.C. State Department of Computer Science

Procedural programming with C

G Programming Languages - Fall 2012

CSCI 171 Chapter Outlines

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

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 4

Functions. Functions are everywhere in C. Pallab Dasgupta Professor, Dept. of Computer Sc & Engg INDIAN INSTITUTE OF TECHNOLOGY KHARAGPUR

Dr M Kasim A Jalil. Faculty of Mechanical Engineering UTM (source: Deitel Associates & Pearson)

Functions. Systems Programming Concepts

C Functions. CS 2060 Week 4. Prof. Jonathan Ventura

C Functions. 5.2 Program Modules in C

Functions. Autumn Semester 2009 Programming and Data Structure 1. Courtsey: University of Pittsburgh-CSD-Khalifa

JTSK Programming in C II C-Lab II. Lecture 3 & 4

COMP322 - Introduction to C++ Lecture 02 - Basics of C++

Functions. Angela Chih-Wei Tang ( 唐之瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan.

TDDE18 & 726G77. Functions

EL6483: Brief Overview of C Programming Language

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

PROGRAMMAZIONE I A.A. 2017/2018

Unit 7. Functions. Need of User Defined Functions

CSE123. Program Design and Modular Programming Functions 1-1

Features of C. Portable Procedural / Modular Structured Language Statically typed Middle level language

Lecture 2: C Programming Basic

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

Functions. printf( %f cubed is %f,x,cube(x)); return 0; } return parameter type double cube(double var) { return (var*var*var);

Functions and Recursion

Instantiation of Template class

EL2310 Scientific Programming

Why Pointers. Pointers. Pointer Declaration. Two Pointer Operators. What Are Pointers? Memory address POINTERVariable Contents ...

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

G Programming Languages Spring 2010 Lecture 4. Robert Grimm, New York University

Fundamental Data Types. CSE 130: Introduction to Programming in C Stony Brook University

CS240: Programming in C

Writing an ANSI C Program Getting Ready to Program A First Program Variables, Expressions, and Assignments Initialization The Use of #define and

EL2310 Scientific Programming

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

Implementing Subprograms

advanced data types (2) typedef. today advanced data types (3) enum. mon 23 sep 2002 defining your own types using typedef

BASIC ELEMENTS OF A COMPUTER PROGRAM

CME 112- Programming Languages II. Week 1 Introduction, Scope Rules and Generating Random Numbers

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

Programming in C. What is C?... What is C?

Topic 6: A Quick Intro To C

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

C Programming Review CSC 4320/6320

cs3157: another C lecture (mon-21-feb-2005) C pre-processor (3).

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

CHAPTER 4 FUNCTIONS. 4.1 Introduction

CS3157: Advanced Programming. Outline

Matlab? Chapter 3-4 Matlab and IPT Basics. Working Environment. Matlab Demo. Array. Data Type. MATLAB Desktop:

Tokens, Expressions and Control Structures

Dynamic memory allocation

CMPE-013/L. Introduction to C Programming

Programs in memory. The layout of memory is roughly:

CS349/SE382 A1 C Programming Tutorial

Everything Else C Programming and Software Tools. N.C. State Department of Computer Science

Variables in C. Variables in C. What Are Variables in C? CMSC 104, Fall 2012 John Y. Park

Programming. Functions and File I/O

Technical Questions. Q 1) What are the key features in C programming language?

C++ Important Questions with Answers

Introduction to C++ Introduction. Structure of a C++ Program. Structure of a C++ Program. C++ widely-used general-purpose programming language

CSE351 Winter 2016, Final Examination March 16, 2016

ภาคการศ กษาท 1 ป การศ กษา 2556

C Review. MaxMSP Developers Workshop Summer 2009 CNMAT

Debugging Techniques. CEFET Engineering Week

BSM540 Basics of C Language

EC 413 Computer Organization

Introduction to C++ with content from

Subject: Fundamental of Computer Programming 2068

C-Programming. CSC209: Software Tools and Systems Programming. Paul Vrbik. University of Toronto Mississauga

Agenda. Peer Instruction Question 1. Peer Instruction Answer 1. Peer Instruction Question 2 6/22/2011

Laboratory 2: Programming Basics and Variables. Lecture notes: 1. A quick review of hello_comment.c 2. Some useful information

Fast Introduction to Object Oriented Programming and C++

Introduction to C/C++ Programming

Lesson 5: Functions and Libraries. EE3490E: Programming S1 2018/2019 Dr. Đào Trung Kiên Hanoi Univ. of Science and Technology

Applied Programming and Computer Science, DD2325/appcs15 PODF, Programmering och datalogi för fysiker, DA7011

Agenda. Components of a Computer. Computer Memory Type Name Addr Value. Pointer Type. Pointers. CS 61C: Great Ideas in Computer Architecture

When you add a number to a pointer, that number is added, but first it is multiplied by the sizeof the type the pointer points to.

Class Information ANNOUCEMENTS

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Bernhard Boser & Randy Katz

Functions. CS10001: Programming & Data Structures. Sudeshna Sarkar Professor, Dept. of Computer Sc. & Engg., Indian Institute of Technology Kharagpur

Subject: PROBLEM SOLVING THROUGH C Time: 3 Hours Max. Marks: 100

CS 61C: Great Ideas in Computer Architecture. Lecture 3: Pointers. Krste Asanović & Randy Katz

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

Lecture 3. Review. CS 141 Lecture 3 By Ziad Kobti -Control Structures Examples -Built-in functions. Conditions: Loops: if( ) / else switch

Goal of lecture. Object-oriented Programming. Context of discussion. Message of lecture

Compiling and Running a C Program in Unix

CSE 431S Type Checking. Washington University Spring 2013

Recursion. Data and File Structures Laboratory. DFS Lab (ISI) Recursion 1 / 20

Introduction to Linked Lists

So far, system calls have had easy syntax. Integer, character string, and structure arguments.

Transcription:

Functions in C C Programming and Software Tools N.C. State Department of Computer Science Functions in C Functions are also called subroutines or procedures One part of a program calls (or invokes the execution of) the function Example: printf() int main(void) (void) printf (); caller Similar to Java methods, but not associated with a class int printf() code for printf callee CSC230: C and Software Tools (c) NC State University CSC Faculty 2 1

Are Functions Necessary? Alternative: just copy the source code of printf() into the caller, everywhere it is called this is called inlining the function code Ex.: int main(void) code for printing something code for printing something else code for printing something else CSC230: C and Software Tools (c) NC State University CSC Faculty 3 Reasons to Inline There is overhead in each function call 1. saving return address and register values 2. allocating space on the stack for local variables and copying their values 3. jumping to new instruction 4. reversing all of the above when returning control to caller inlined code can be stripped down for the particular inputs expected CSC230: C and Software Tools (c) NC State University CSC Faculty 4 2

Reasons to Use Functions Functions improve modularity reduce duplication, inconsistency improve readability, easier to understand simplifies debugging test parts unit testing then the whole system/functional testing Allows creation of libraries of useful "building blocks" for common processing tasks CSC230: C and Software Tools (c) NC State University CSC Faculty 5 Function Return Values The simplest possible function has no return value and no input parameters, ex.: Useful? void abort (void) The next simplest case: value returned, but no input parameters, ex.: char getchar (void) int rand (void) clock_t clock (void) CSC230: C and Software Tools (c) NC State University CSC Faculty 6 3

What Values Can a Function Return? The datatype of a function can be any of: integer or floating point number structs and unions enumerated constants void pointers to any of the above Each function s type should be declared before use CSC230: C and Software Tools (c) NC State University CSC Faculty 7 Values (cont d) Functions cannot return arrays, nor can they return functions (although they can return pointers to both) int main(void) char s[100]; s[] = readstring(); Illegal do not try! char readstring() [100] CSC230: C and Software Tools (c) NC State University CSC Faculty 8 4

How Many Values Returned? A function can return at most one value What if you need a function to return multiple results? Example: you provide the radius and height of a cylinder to a function, and want to get back 1. surface area and 2. volume of the cylinder CSC230: C and Software Tools (c) NC State University CSC Faculty 9 How Many (cont d) Choice #1: make the return type a struct typedef struct //similar to an object int area; // first field int vol; // second field mystruct; mystruct ans; mystruct cyl (int, int ); int main(void) ans = cyl (r, h); CSC230: C and Software Tools (c) NC State University CSC Faculty 10 5

How Many (cont d) Choice #2: use global variables global variables are visible to (and can be updated by) all functions double area, vol; common source of bugs void cyl (int, int ); use of global variables int main(void) cyl (r, h); void cyl (int r, int h) area = h * (2 * PI * r); vol = h * (r * r * PI); CSC230: C and Software Tools (c) NC State University CSC Faculty 11 How Many (cont d) Choice #3: pass parameters by reference (using pointers), instead of by value allows them to be updated by the function Ex.: later, when we talk about pointers CSC230: C and Software Tools (c) NC State University CSC Faculty 12 6

Function Side Effects Besides the value returned, these are things that may be changed by the execution of the function Examples input to or output by the computer changes to the state of the computer system changes to global variables changes to input parameters (using pointers) There are problems with side effects; we ll come back to this... common source of bugs side effects in functions and expressions CSC230: C and Software Tools (c) NC State University CSC Faculty 13 Input Parameters of a Function Often called arguments of the function Two types formal or abstract parameter declarations in the function definition actual or concrete the actual values passed to the function at run time If no input parameters to the function, leave empty, or use the void keyword CSC230: C and Software Tools (c) NC State University CSC Faculty 14 7

Input Parameters of a Function (cont d) The number and value of actual parameters should match the number and type of formal parameters function prototype int a, v; void cyl (int, int ); int main(void) float r; (void) cyl (r); Caller Oops! actual parameters formal parameters void cyl (int r, int h) a = h * (2 * PI * r); v = h * (r * r * PI); Callee CSC230: C and Software Tools (c) NC State University CSC Faculty 15 Parameter Passing Parameters are passed using call by value (same as Java primitives) i.e., a copy of the parameter value is made and provided to the function Any changes the function makes to this (copied) value have no effect on the caller s variables CSC230: C and Software Tools (c) NC State University CSC Faculty 16 8

Input Parameters (cont d) Ex.: float a, v; void main ( ) int r, h;... (void) cylbigger (r, h);... does not change caller s variables r and h void cylbigger (int r, int h) r = 2 * r; h = 2 * h; a = h * (2 * PI * r); v = h * (r * r * PI); CSC230: C and Software Tools (c) NC State University CSC Faculty 17 Arrays as Local Variables? Arrays can be declared as local variables of functions, e.g.: int main() double smallarray[20]; int i,... for (i < 0; i < 20; i++) smallarray[i] =... Space for local variables is allocated on the stack means: large arrays must be declared as static or global variables otherwise segmentation fault double bigarray[10000000]; int main() int i,... for (i = 0; i < 10000000; i++) bigarray[i] =... CSC230: C and Software Tools (c) NC State University CSC Faculty 18 9

Types for Function Arguments In C, an implicit type conversion occurs if actual argument type disagrees with formal argument type formal void u ( char c ); double g = 12345678.0; u (g); actual g = 12345678.0 c = 78 no compiler warnings! common source of bugs overlooking type differences in parameters Advice: more predictable if you cast it yourself CSC230: C and Software Tools (c) NC State University CSC Faculty 19 Must Declare Function Before Use Program with compilation errors #include <stdio.h> Program without compilation errors #include <stdio.h> int main (void) float w, x, y; w = f(x, y); float f (float x, float y) float f (float x, float y) int main (void) float w, x, y; w = f(x, y); why should this make a difference? CSC230: C and Software Tools (c) NC State University CSC Faculty 20 10

Declare Before... (cont d) Approaches 1. (unusual) locate the function definition at the beginning of the source code file, or 2. (usual) put a function prototype at the beginning of the source code (actual function definition can appear anywhere) CSC230: C and Software Tools (c) NC State University CSC Faculty 21 Declare Before... (cont d) Program without compilation errors #include <stdio.h> float f (float, float ); function prototype int main (void) float w, x, y; w = f(x, y); float f (float x, float y) CSC230: C and Software Tools (c) NC State University CSC Faculty 22 11

Arrays as Function Arguments An array can be passed as an input argument You can specify the array length explicitly in the function declaration Ex.: void getdays (int months[12]) void getdays (int years[10][12]) CSC230: C and Software Tools (c) NC State University CSC Faculty 23 Arrays as Arguments (cont d) Make sure actual argument lengths agree with formal argument lengths! will generate compiler errors otherwise Ex.: int years[5][12]; result = getdays (years); why not years[5][12] here? CSC230: C and Software Tools (c) NC State University CSC Faculty 24 12

Omitting Array Sizes Implicit length for the first dimension of a formal parameter is allowed However, you cannot omit the length of other dimensions OK void days (int years[][12]) NOT OK void days (int years[10][]) CSC230: C and Software Tools (c) NC State University CSC Faculty 25 Dynamic Array Size Declaration Q: How can you tell how big the array is if its size is implicit? A: You provide array size as an input parameter to the function Ex.: void days (int nm, int months[]) OR void days (int nm, int months[nm]) Note: make sure the size parameter comes before the array parameter CSC230: C and Software Tools (c) NC State University CSC Faculty 26 13

Dynamic Array Size (cont d) void days(int ny, int nm, int years[ny][nm]) for ( i = 0 ; i < ny ; i++) for ( j = 0; j < nm ; j++) dcnt += years[i][j]; Just make sure sizes are consistent with array declaration int years[10][12]; problem here! common source of bugs (void) days(20,12, years); mismatches in array size declarations CSC230: C and Software Tools (c) NC State University CSC Faculty 27 Arrays as Parameters Arrays are passed BY REFERENCE, not by value i.e., the callee function can modify the caller s array values Therefore, if you update values in an array passed to a function, you areupdating the caller s array int years[10][12]; common source of bugs confusion about call by reference vs. (void) changedays(years); call by value void changedays (int inyears[10][12]) inyears[1][7] = 29; CSC230: C and Software Tools (c) NC State University CSC Faculty 28 14

Checking Input Parameters for Errors Who should check for errors: caller or callee? advantages of caller checking for errors? advantages of callee checking for errors? a = 26; b = 0; c = divide (a, b); Caller common source of bugs failure to check inputs for errors int divide (int x, int y) return (x / y) ; Callee CSC230: C and Software Tools (c) NC State University CSC Faculty 29 Variable Number of Arguments? Q: If a function takes a variable number of arguments (ex.: printf()), how do you specify that in a function prototype? A: Use ellipses to indicate unknown number of (additional) input parameters int printf(), or int printf(*s, ) How do you specify a variable number of arguments in the function definition? to be discussed later CSC230: C and Software Tools (c) NC State University CSC Faculty 30 15

Side Effects, Again Q: If a variable is referenced multiple times in a single statement, and modified (by side effects) one of those times, do the other references see the side effect? Ex.: a = 2; b = ++a; c = a + a; x = 1; b = --x && x; a = 2; if (a++) b = a; a = 2; b = ++a + a; a = 2; b = f( ++a, a); a = 2; b = ++a, c = a; a = 2; x = (++a > 2)? a : 5; CSC230: C and Software Tools (c) NC State University CSC Faculty 31 Side Effects (cont d) Complete set of sequence points for C statement termination ; closing parent in a condition evaluation ) the following operators: a&&b a b a?b:c a,b after evaluation of all arguments to a function call after returning a value from a function Advice: avoid having multiple references to a variable in a single statement if one of those references has side effects CSC230: C and Software Tools (c) NC State University CSC Faculty 32 16

Functions Calling Functions f() calls g() calls h() calls i() calls j() calls Is there such a thing as having too many layers, or too deep a calling stack? Disadvantages? CSC230: C and Software Tools (c) NC State University CSC Faculty 33 Recursion What about f() calling f()??? A powerful and flexible way to iteratively compute a value although this idea seems modest, recursion is one of the most important concepts in computer science Each iteration must temporarily store some input or intermediate values while waiting for the results of recursion to be returned common source of bugs misunderstanding of recursion CSC230: C and Software Tools (c) NC State University CSC Faculty 34 17

Recursion Example... int main (void) int n = 3; w = factorial ( n ); int factorial (int n) if (n == 1) return 1; else return n * factorial(n-1); CSC230: C and Software Tools (c) NC State University CSC Faculty 35 Example (cont d) calls factorial(3) main() calls factorial(2), stores n=3 returns 3 * 2 * 1 factorial(3) returns 2 * 1 factorial(2) calls factorial(1), stores n=2 returns 1 factorial(1) CSC230: C and Software Tools (c) NC State University CSC Faculty 36 18

Recursion... (etc) What does the function f(n) = f(n 1) + f(n 2) (and f(1) == f(0) == 1) return for n = 5? long long int f (long long int n) if ((n == 1) (n == 0)) return 1; else return (f(n-1) + f(n-2)); what function is this? any problems if n = 50? code it and try! CSC230: C and Software Tools (c) NC State University CSC Faculty 37 Recursion or Iteration? Every recursion can be rewritten as a combination of 1. a loop (iteration), plus 2. storage (a stack) for intermediate values CSC230: C and Software Tools (c) NC State University CSC Faculty 38 19

Iterative Version of f() #include <stdio.h> int i; int main (void) static int n = 50; long long int f[n]; //stack better? worse? f[0] = f[1] = 1; for (i = 2; i < n; i++) f[i] = f[i-1] + f[i-2]; printf( %lld\n, f[n]); return 0; CSC230: C and Software Tools (c) NC State University CSC Faculty 39 How Big Should A Function Be? Too small (100 line program, 20 functions)??? Too large (10,000 line program with 2 functions)??? Just right? (Linux recommendations) Functions should... do just one thing...[and] fit on one or two screenfuls of text... the number of local variables [for a function]... shouldn't exceed 5 10 CSC230: C and Software Tools (c) NC State University CSC Faculty 40 20

Top Down Programming in C Procedural programming languages encourage a way of structuring your programs: start with the basics then progressively fill in the details Ex.: writing a web browser how does one get started on a large program like this? CSC230: C and Software Tools (c) NC State University CSC Faculty 41 The C Standard Library Small set of useful functions, standardized on all platforms Definitions are captured in 24 header files Today: how to generate random numbers needed for cryptography, games of chance, simulation, probability, etc CSC230: C and Software Tools (c) NC State University CSC Faculty 42 21

<stdlib.h>: Random Numbers The <stdlib.h> library header defines: int rand(void) returns pseudo random number in range 0 to RAND_MAX void srand(unsigned int seed) uses seed to generate new sequence of pseudorandom numbers RAND_MAX Maximum value returned by rand() Don't forget: #include <stdlib.h> CSC230: C and Software Tools (c) NC State University CSC Faculty 43 Random Numbers (cont'd) To seed the random number generator (void) srand( (unsigned) time (NULL) ); where time() is defined in <time.h> To generate a random (real) number r2 in the (real number) range minmax: double min =, max = ; double range = max min; double r1 = ((double) rand() / (double) RAND_MAX) * range; double r2 = r1 + min; CSC230: C and Software Tools (c) NC State University CSC Faculty 44 22

Example To generate a number in the interval [0.0,1.0) #include <stdio.h> #include <stdlib.h> #include <time.h> double getrand() int r = rand(); return ((double) r / (RAND_MAX + 1)); int main () (void) srand( time (NULL) ); double r = getrand(); CSC230: C and Software Tools (c) NC State University CSC Faculty 45 23