Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan.

Slides:



Advertisements
Similar presentations
Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Advertisements

Spring Semester 2013 Lecture 5
1 ICS103 Programming in C Lecture 5: Introduction to Functions.
Fungsi Risanuri Hidayat, Ir., M.Sc.. Functions C usually consist of two things: instance variables and functions. All C programs consist of one or more.
Functions and InterfacesCS-2303, C-Term Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming.
Numerical Computation Review and Continuation CS-2301, B-Term Numerical Computation in C Review and Continuation CS-2301, System Programming for.
Introduction to FunctionsCS-2301 D-term Introduction to Functions CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming.
Loose endsCS-2301, B-Term “Loose Ends” CS-2301, System Programming for Non-Majors (Slides include materials from The C Programming Language, 2 nd.
"Loose ends"CS-2301 D-term “Loose Ends” CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming Language, 2 nd edition,
Introduction to FunctionsCS-2301 B-term Introduction to Functions CS-2301, System Programming for Non-majors (Slides include materials from The.
CS 201 Functions Debzani Deb.
Top-Down Design with Functions 4 What do programmer’s (not programs!) use as input to the design of a program? –Documentation Problem definition Requirements.
Scope Rules and Storage Types CS-2303, C-Term Scope Rules and Storage Types CS-2303, System Programming Concepts (Slides include materials from The.
Conditionals, Loops, and Other Statements CS-2301 D-term Conditionals, Loops, and Other Kinds of Statements CS-2301 System Programming C-term 2009.
Introduction to Classes and Objects CS-2303, C-Term Introduction to Classes and Objects CS-2303 System Programming Concepts (Slides include materials.
Introduction to C Programming
Assignment #2, 12- month Calendar CS-2301, B-Term Programming Assignment #2 12-Month Calendar CS-2301, System Programming for Non-Majors (Slides.
Conditionals, Loops, and Other Statements CS-2301, B-Term Conditionals, Loops, and Other Kinds of Statements CS-2301, System Programming for Non-Majors.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
Covenant College November 27, Laura Broussard, Ph.D. Professor COS 131: Computing for Engineers Chapter 5: Functions.
C++ Programming Lecture 9 Functions – Part I By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department.
Introduction to FunctionsCIS 1057 Fall Introduction to Functions CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based.
FUNCTIONS. Midterm questions (1-10) review 1. Every line in a C program should end with a semicolon. 2. In C language lowercase letters are significant.
ECE 103 Engineering Programming Chapter 30 C Functions Herbert G. Mayer, PSU CS Status 8/9/2014 Initial content copied verbatim from ECE 103 material developed.
Lesson #6 Modular Programming and Functions.
Chapter 6: Modular Programming
Chapter 2 - Introduction to C Programming
Lesson #6 Modular Programming and Functions.
Functions, Part 2 of 2 Topics Functions That Return a Value
Programming Languages and Paradigms
Quiz 11/15/16 – C functions, arrays and strings
Programming Fundamentals Lecture #7 Functions
Programming Paradigms
Chapter 2 - Introduction to C Programming
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Formatted and Unformatted Input/Output Functions
Chapter 5 - Functions Outline 5.1 Introduction
Lesson #6 Modular Programming and Functions.
User Defined Functions
Classes, Constructors, etc., in C++
Miscellaneous C++ Topics
Dynamic Memory Allocation (and Multi-Dimensional Arrays)
Structures, Unions, and Typedefs
Binary Trees (and Big “O” notation)
Programming Assignment #1 12-Month Calendar—
Symbolic Constants in C
Recursion and Implementation of Functions
Scope Rules and Storage Types
Programming Assignment #5
Differences between Java and C
Elements of a Python Program
Your first C and C++ programs
Operator Overloading Professor Hugh C. Lauer CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2nd edition,
Lesson #6 Modular Programming and Functions.
Digression on Loop Invariants
Function.
Introduction to Problem Solving and Programming
A Deeper Look at Classes
Programming Languages and Paradigms
Introduction to C Programming
Function.
Functions, Part 2 of 3 Topics Functions That Return a Value
CPS125.
Introduction to Classes and Objects
Presentation transcript:

Functions in C and C++ CS-2303 System Programming Concepts Hugh C. Lauer (Slides include materials from The C Programming Language, 2nd edition, by Kernighan and Ritchie, Absolute C++, by Walter Savitch, The C++ Programming Language, Special Edition, by Bjarne Stroustrup, and from C: How to Program, 5th and 6th editions, by Deitel and Deitel) CS-2303, A-Term 2012 Functions in C and C++

Definition – Function A fragment of code that accepts zero or more argument values, produces a result value, and has zero or more side effects. A means of encapsulating a subset of a program or a system To hide details To be invoked from multiple places To share with others A function in C is equivalent to a method in Java, but without the surrounding class CS-2303, A-Term 2012 Functions in C and C++ 2

Functions – a big Topic Examples Function definition Function prototypes & Header files Pre- and post-conditions Scope rules and storage classes Implementation of functions Recursive functions CS-2303, A-Term 2012 Functions in C and C++ 3

Reading Assignment Chapter 4 of K&R CS-2303, A-Term 2012 Functions in C and C++

Common Functions in C #include <math.h> #include <stdio.h> sin(x) // radians cos(x) // radians tan(x) // radians atan(x) atan2(y,x) /* atan(y/x), even when x == 0 */ exp(x) // ex log(x) // loge x log10(x) // log10 x sqrt(x) // x  0 pow(x, y) // xy ... #include <stdio.h> printf() fprintf() scanf() sscanf() ... #include <string.h> strcpy() strcat() strcmp() strlen() CS-2303, A-Term 2012 Functions in C and C++ 5

Common Functions (continued) In K&R <assert.h> // for diagnostics, loop invariants, etc. <stdarg.h> // for parsing arguments <time.h> // time of day and elapsed time <limits.h> // implementation dependent numbers <float.h> // implementation dependent numbers <setjmp.h> // beyond scope of this course <signal.h> // beyond scope of this course CS-2303, A-Term 2012 Functions in C and C++ 6

Common Functions (continued) See also the man pages of your system for things like <pthread.h> // concurrent execution <socket.h> // network communications ... // many, many other facilities Fundamental Rule: if there is a chance that someone else had same problem as you, … … there is probably a package of functions to solve it in C! CS-2303, A-Term 2012 Functions in C and C++ 7

Functions in C resultType functionName(type1 param1, type2 param2, …) { … body } If no result, resultType should be void Warning if not! If no parameters, use void between () CS-2303, A-Term 2012 Functions in C and C++ 8

Functions in C resultType functionName(type1 param1, type2 param2, …) { … body } //functionName If no result, resultType should be void Warning if not! If no parameters, use void between () It is good style to end a function with a comment showing its name CS-2303, A-Term 2012 Functions in C and C++ 9

N = f(pi*pow(r,2), b+c) + d; Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; CS-2303, A-Term 2012 Functions in C and C++

Definitions Parameter:– a declaration of an identifier within the '()' of a function declaration Used within the body of the function as a variable of that function Initialized by the caller to the value of the corresponding argument. Argument:– an expression passed when a function is called; becomes the initial value of the corresponding parameter Note: Changes to parameters within the function do not propagate back to caller! All parameters “call by value,” — as in Java CS-2303, A-Term 2012 Functions in C and C++

N = f(pi*pow(r,2), b+c) + d; Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr1, expr2) can be used in any expression where a value of type int can be used – e.g., N = f(pi*pow(r,2), b+c) + d; These are parameters These are arguments CS-2303, A-Term 2012 Functions in C and C++

Parameters and Arguments Parameters are variables (or constants) that can be used inside of functions Arguments are expressions that are evaluated at call time and use to initialize parameters CS-2303, A-Term 2012 Functions in C and C++

Note Functions in C do not allow other functions to be declared within them Like C++, Java Unlike Algol, Pascal All functions defined at “top level” of C programs (Usually) visible to linker Can be linked by any other program that knows the function prototype Can “see” anything declared previously in same program (or in an included interface) CS-2303, A-Term 2012 Functions in C and C++

Note on printf parameters int printf(char *s, ...) { body } // printf In this function header, “…” is not a professor’s shorthand (as often used in these slides) …but an actual sequence of three dots (no spaces between) Meaning:– the number and types of arguments is indeterminate Use <stdarg.h> to extract the arguments Also scanf(char *s, …); CS-2303, A-Term 2012 Functions in C and C++ 15

Questions? CS-2303, A-Term 2012 Functions in C and C++ 16

Function Prototypes There are many, many situations in which a function must be used separate from where it is defined – before its definition in the same C program In one or more completely separate C programs This is actually the normal case! Therefore, we need some way to declare a function separate from defining its body. Called a Function Prototype CS-2303, A-Term 2012 Functions in C and C++ 17

Function Prototypes (continued) Definition:– a Function Prototype in C is a language construct of the form:– return-type function-name (parameter declarations) ; I.e., exactly like a function definition, except with a ';' instead of a body in curly brackets Essentially, the method of a Java interface. aka function header CS-2303, A-Term 2012 Functions in C and C++ 18

Purposes of Function Prototype So compiler knows how to compile calls to that function, i.e., number and types of arguments type of result … without knowing anything about how it is defined! As part of a “contract” between developer and programmer who uses the function As part of hiding details of how it works and exposing what it does. A function header serves as a “black box.” CS-2303, A-Term 2012 Functions in C and C++ 19

Questions? CS-2303, A-Term 2012 Functions in C and C++

“Contract” between Developer and User of a Function Function Prototype The pre- and post-conditions I.e., assertions about what is true before the function is called and what is true after it returns. A logical way of explaining what the function does CS-2303, A-Term 2012 Functions in C and C++ 21

Definitions Pre-condition:–a characterization or logical statement about the values of the parameters, and values of relevant variables outside the function prior to calling the function Post-condition:–a logical statement or characterization about the result of the function in relation to the values of the parameters and pre-conditions, and changes to values of variables outside the function after the function returns CS-2303, A-Term 2012 Functions in C and C++ 22

Example 1 double sin (double angle); Pre:– angle is expressed in radians Post:– result is the familiar sine of angle Note: this function does not use or change any other variables CS-2303, A-Term 2012 Functions in C and C++ 23

Example 2 int printf (string, arg1, arg2, …) Pre:– string is terminated with '\0' and contains conversion specifiers Pre:– a buffer maintained by the file system contains zero or more unprinted characters from previous calls. Post:– args are substituted for conversion codes in copy of string; resulting string is added to buffer Post:– if '\n' is anywhere in buffer, line is “printed” up to '\n'; printed characters are cleared from buffer Post:– result is number of characters added to buffer by printf CS-2303, A-Term 2012 Functions in C and C++ 24

Example 3 float total = 0; int count = 0; int GetItem(void) { float input; int rc; printf("Enter next item:- "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // GetNewItem CS-2303, A-Term 2012 Functions in C and C++ 25

Example 3 Pre:– total is sum of all previous inputs, or zero if none Pre:– count is number of previous inputs, or zero if none Post:– if valid input is received total = totalprev + input, count = countprev + 1 float total = 0; int count = 0; int GetItem(void) { float input; int rc; printf("Enter next item:- "); if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; }; // if return rc; } // GetNewItem CS-2303, A-Term 2012 Functions in C and C++ 26

Important Pre- and post-conditions are analogous to loop invariants I.e., they describe something about the data before and after a function is called and the relationship that the function preserves Often are used together with loop invariants … to show that loop invariant is preserved from one iteration to the next CS-2303, A-Term 2012 Functions in C and C++ 27

Questions? Next Topic CS-2303, A-Term 2012 Functions in C and C++ 28