Functions and InterfacesCS-2303, C-Term 20101 Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming.

Slides:



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

Lecture 2 Introduction to C Programming
Introduction to C Programming
 2000 Prentice Hall, Inc. All rights reserved. Chapter 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line.
Introduction to C Programming
Numerical Computation Review and Continuation CS-2301, B-Term Numerical Computation in C Review and Continuation CS-2301, System Programming for.
Differences between Java and C CS-2303, C-Term Differences between Java and C CS-2303, System Programming Concepts (Slides include materials from.
C Programming Language 4 Developed in 1972 by Dennis Ritchie at AT&T Bell Laboratories 4 Used to rewrite the UNIX operating system 4 Widely used on UNIX.
Introduction to FunctionsCS-2301 D-term Introduction to Functions CS-2301 System Programming C-term 2009 (Slides include materials from The C Programming.
1 Lecture 2  Input-Process-Output  The Hello-world program  A Feet-to-inches program  Variables, expressions, assignments & initialization  printf()
 2007 Pearson Education, Inc. All rights reserved Introduction to C Programming.
"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.
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.
Guide To UNIX Using Linux Third Edition
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.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
Conditionals, Loops, and Other Statements CS-2301, B-Term Conditionals, Loops, and Other Kinds of Statements CS-2301, System Programming for Non-Majors.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
By: Mr. Baha Hanene Chapter 3. Learning Outcomes We will cover the learning outcome 02 in this chapter i.e. Use basic data-types and input / output in.
Chapter 4:Functions| SCP1103 Programming Technique C | Jumail, FSKSM, UTM, 2005 | Last Updated: September 2005 Slide 1 Functions Lecture 4 by Jumail Bin.
CS 11 C track: lecture 1 Preliminaries Need a CS cluster account cgi-bin/sysadmin/account_request.cgi Need to know UNIX ITS.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Programming With C.
CMSC 104, Version 9/011 Introduction to C Topics Compilation Using the gcc Compiler The Anatomy of a C Program 104 C Programming Standards and Indentation.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 2 Chapter 2 - Introduction to C Programming.
Introduction to C Programming Angela Chih-Wei Tang ( 唐 之 瑋 ) Department of Communication Engineering National Central University JhongLi, Taiwan 2010 Fall.
Programming Fundamentals. Today’s Lecture Why do we need Object Oriented Language C++ and C Basics of a typical C++ Environment Basic Program Construction.
COMPUTER PROGRAMMING. A Typical C++ Environment Phases of C++ Programs: 1- Edit 2- Preprocess 3- Compile 4- Link 5- Load 6- Execute Loader Primary Memory.
1 ICS103 Programming in C Lecture 7: Introduction to Functions.
Algorithms  Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Introduction to FunctionsCIS 1057 Fall Introduction to Functions CIS 1057 Computer Programming in C Fall 2013 (Acknowledgement: Many slides based.
CSCI 3133 Programming with C Instructor: Bindra Shrestha University of Houston – Clear Lake.
Chapter 10: Classes and Data Abstraction. Objectives In this chapter, you will: Learn about classes Learn about private, protected, and public members.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. 1 Chapter 2 - Introduction to C Programming Outline.
A First Book of ANSI C Fourth Edition Chapter 6 Modularity Using Functions: Part I.
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.
Chapter 10: Classes and Data Abstraction. Classes Object-oriented design (OOD): a problem solving methodology Objects: components of a solution Class:
 2007 Pearson Education, Inc. All rights reserved. A Simple C Program 1 /* ************************************************* *** Program: hello_world.
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.
1 Lecture 2 - Introduction to C Programming Outline 2.1Introduction 2.2A Simple C Program: Printing a Line of Text 2.3Another Simple C Program: Adding.
Introduction to C Topics Compilation Using the gcc Compiler
CSCE 206 Structured Programming in C
Chapter 2 - Introduction to C Programming
Algorithms Problem: Write pseudocode for a program that keeps asking the user to input integers until the user enters zero, and then determines and outputs.
Chapter 2 - Introduction to C Programming
Computer Science 210 Computer Organization
Chapter 2 - Introduction to C Programming
Chapter 2 - Introduction to C Programming
Introduction to C Topics Compilation Using the gcc Compiler
Program Breakdown, Variables, Types, Control Flow, and Input/Output
Chapter 2 - Introduction to C Programming
Scope Rules and Storage Types
Your first C and C++ programs
Homework Applied for cs240? (If not, keep at it!) 8/10 Done with HW1?
C Programming Getting started Variables Basic C operators Conditionals
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.
Function.
Introduction to C Topics Compilation Using the gcc Compiler
Chapter 2 - Introduction to C Programming
Programming Languages and Paradigms
Introduction to C Programming
Function.
Introduction to Classes and Objects
Presentation transcript:

Functions and InterfacesCS-2303, C-Term Functions and Interfaces in C CS-2303, System Programming Concepts (Slides include materials from The C Programming Language, 2 nd edition, by Kernighan and Ritchie and from C: How to Program, 5 th and 6 th editions, by Deitel and Deitel)

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; }

Functions and InterfacesCS-2303, C-Term Fundamental Rule in C Every identifier must be declared before it can be used in a program Definition:– “identifier” A sequence of letters, digits, and ‘_’ Must begin with a letter or ‘_’ Case is significant –Upper and lower case letters are different Must not be a “reserved word” — see p. 192 of K&R Definition:– “declare” Introduce an identifier and the kind of entity it refers to Optionally, define associated memory or program

Functions and InterfacesCS-2303, C-Term So where is printf declared? #include int main (void) { printf(″Hello, World!\n″); return 0; } Answer: in this file!

Functions and InterfacesCS-2303, C-Term #include Logically:– Equivalent to an interface in Java I.e., where types and functions are declared Physically:– A file of C code that is copied into your program at compile time –By the C preprocessor Spells out the contract of the interface between implementer and client aka Header file

Functions and InterfacesCS-2303, C-Term #include Declares everything that your program needs to know about the “standard I/O facilities” of C … … and conceals everything that your program does not need to know about those same facilities Doesn’t change very often And when it does change, every program that depends on it must be recompiled!

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; } Body of the function Defines what the function “does” Sequence of statements Each does a step of the function Enclosed in curly brackets { } Indistinguishable from a compound statement

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; } Call to another function In this case, a function defined by the system Prints some data on standard output

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; } Argument to printf – a constant string Enclosed in straight double quotes Note the new-line character ′\n′ at the end

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; } A return statement return is a reserved word in C main should return zero if no error; non-zero if error

Functions and InterfacesCS-2303, C-Term Your First C Program #include int main (void) { printf(″Hello, World!\n″); return 0; } Note that statements typically end with semicolons So compiler can tell where end of statement is

Functions and InterfacesCS-2303, C-Term Questions? Write, compile, and execute this program in Lab session today and tomorrow

Functions and InterfacesCS-2303, C-Term What happens to your program … …after it is compiled, but before it can be run?

Functions and InterfacesCS-2303, C-Term Example #include int main (void) { printf (″Hello,″ ″ world\n″); return 0; } Symbol defined in your program and used elsewhere main Symbol defined elsewhere and used by your program printf

Functions and InterfacesCS-2303, C-Term Static Linking and Loading Printf.c Printf.o Library gcc ar Linker Memory HelloWorld.c gcc HelloWorld.o Loader a.out (or file name of your command)

Functions and InterfacesCS-2303, C-Term Static Linking and Loading Linker Printf.c Printf.o Library gcc ar Memory HelloWorld.c gcc HelloWorld.o Loader a.out (or file name of your command) Part of gcc

Functions and InterfacesCS-2303, C-Term Static Linking and Loading Linker Printf.c Printf.o Library gcc ar Memory HelloWorld.c gcc HelloWorld.o Loader a.out (or file name of your command) Part of gcc Part of operating system

Functions and InterfacesCS-2303, C-Term Compiling Your Program gcc HelloWorld.c Compiles the program in HelloWorld.c, links with any standard libraries, puts executable in a.out You should find HelloWorld.o in your directory gcc –o hello_world HelloWorld.c Same as above, but names the executable file hello_world instead of a.out gcc –lrt HelloWorld.c Searches library named rt.a for functions to link (in addition to standard libraries)

Functions and InterfacesCS-2303, C-Term Compiling Your Program (continued) gcc foo.c bar.c help.c Compiles the programs foo.c, bar.c, and help.c, links with standard libraries, executable in a.out You should find foo.o, bar.o, and help.o in your directory gcc –o Lab2 foo.c bar.c help.c Same as above, but names the executable file Lab2 gcc –c foo.c bar.c help.c Compiles foo.c, bar.c, and help.c to foo.o, bar.o, and help.o but does not link together gcc –o Lab2 foo.o bar.o help.o Links together previously compiled foo.o, bar.o, help.o, stores result in Lab2

Functions and InterfacesCS-2303, C-Term Questions?

Functions and InterfacesCS-2303, C-Term 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 method 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

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term Textbook References Chapter 4 of K&R Chapter 5 of D&D

Functions and InterfacesCS-2303, C-Term Common Functions in C #include –sin(x) // radians –cos(x) // radians –tan(x) // radians –atan(x) –atan2(y,x) –exp(x) // e x –log(x) // log e x –log10(x) // log 10 x –sqrt(x) // x  0 –pow(x, y) // x y –... #include –printf() –fprintf() –scanf() –sscanf() –... #include –strcpy() –strcat() –strcmp() –strlen() –...

Functions and InterfacesCS-2303, C-Term Common Functions (continued) In K&R, also in D&D – // for diagnostics, loop invariants, etc. – // for parsing arguments – // time of day and elapsed time – // implementation dependent numbers – // implementation dependent numbers. – // beyond scope of this course

Functions and InterfacesCS-2303, C-Term Common Functions (continued) See also the man pages of your system for things like // concurrent execution // 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!

Functions and InterfacesCS-2303, C-Term Functions in C resultType functionName( type 1 param1, type 2 param2, …) { … body … } If no result, resultType should be void Warning if not! If no parameters, use void between ()

Functions and InterfacesCS-2303, C-Term Functions in C resultType functionName( type 1 param1, type 2 param2, …) { … body … }// functionName If no result, resultType should be void Warning if not! If no parameters, use void between () It is good style to always end a function with a comment showing its name

Functions and InterfacesCS-2303, C-Term Using Functions Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr 1, expr 2 ) 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;

Functions and InterfacesCS-2303, C-Term Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr 1, expr 2 ) 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; Using Functions (continued) This is a parameter This is an argument This is also an argument

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term 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 in C are “call by value.”

Functions and InterfacesCS-2303, C-Term Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr 1, expr 2 ) 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; Using Functions (continued) The first argument expression is evaluated, converted to double, and assigned to parameter x The second argument expression is evaluated, converted to int, and assigned to parameter a

Functions and InterfacesCS-2303, C-Term Let int f(double x, int a) be (the beginning of) a declaration of a function. Then f(expr 1, expr 2 ) 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; Using Functions (continued) Function f is executed and returns a value of type int Result of f is added to d Sum is assigned to N

Functions and InterfacesCS-2303, C-Term 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)

Functions and InterfacesCS-2303, C-Term 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 to extract the arguments

Functions and InterfacesCS-2303, C-Term Questions?

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term Purposes of Function Prototype So compiler knows how to compile calls to that function, i.e., –number and types of arguments –type of result 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 serves as a “black box.”

Functions and InterfacesCS-2303, C-Term Questions?

Functions and InterfacesCS-2303, C-Term “Contract” between Developer and User of a Function 1.Function Prototype 2.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

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term Example 2 int printf (string, arg 1, arg 2, …) –Pre:– string terminated with '\0' and containing 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

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term Example 3 float total = 0; int count = 0; int GetItem(void) { float input; int rc;...; if ((rc = scanf("%f", &input)) != EOF && (rc > 0)) { total += input; count++; };// if return rc; }// GetItem 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 = total prev + input, count = count prev + 1

Functions and InterfacesCS-2303, C-Term 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

Functions and InterfacesCS-2303, C-Term Questions?