Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.

Slides:



Advertisements
Similar presentations
Lecture 3 Some commonly used C programming tricks. The system command Project No. 1: A warm-up project.
Advertisements

Etter/Ingber Engineering Problem Solving with C Fundamental Concepts Chapter 4 Modular Programming with Functions.
Introduction to C Programming
Lecture 20 Arrays and Strings
Exceptions, Templates, And The Standard Template Library (STL) Chapter 16.
1 Lecture13: Other C Topics 12/17/2012. Topics Variable-length argument lists Pointers to functions Command-line arguments Suffixes for integer and floating-point.
Chapter 14 - Advanced C Topics Associate Prof. Yuh-Shyan Chen Dept. of Computer Science and Information Engineering National Chung-Cheng University.
Kernighan/Ritchie: Kelley/Pohl:
6/10/2015C++ for Java Programmers1 Pointers and References Timothy Budd.
Unix Continuum of Tools Do something once: use the command line Do something many times: –Use an alias –Use a shell script Do something that is complex.
Declaring Arrays Declare an array of 10 elements: int nums[10]; Best practice: #define SIZE 10 int nums[SIZE]; // cannot be int[SIZE] nums; C99: int nums[someVariable]
Introduction to C Programming Overview of C Hello World program Unix environment C programming basics.
Chapter 6 C Arrays Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education Inc. Arrays are data structures.
CMSC 104, Version 8/061L18Functions1.ppt Functions, Part 1 of 4 Topics Using Predefined Functions Programmer-Defined Functions Using Input Parameters Function.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
Computer Science 210 Computer Organization Introduction to C.
C How to Program, 7/e © by Pearson Education, Inc. All Rights Reserved.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
C Programming Tutorial – Part I CS Introduction to Operating Systems.
C How to Program, 6/e © by Pearson Education, Inc. All Rights Reserved.
17. ADVANCED USES OF POINTERS. Dynamic Storage Allocation Many programs require dynamic storage allocation: the ability to allocate storage as needed.
ITEC 320 C++ Examples.
C Programming in Linux Jacob Chan. C/C++ and Java  Portable  Code written in one system and works in another  But in C, there are some libraries that.
Functions Top-down design Breaking a complex problem into smaller parts that we can understand is a common practice. The process of subdividing a problem.
File IO and command line input CSE 2451 Rong Shi.
1 CHAPTER 5 POINTER. 2 Pointers  Basic concept of pointers  Pointer declaration  Pointer operator (& and *)  Parameter passing by reference  Dynamic.
Lecture 3: Getting Started & Input / Output (I/O) “TRON” Copyright 1982 (Walt Disney Productions)
19&20-2 Know how to declare pointer variables. Understand the & (address) and *(indirection) operators. Dynamic Memory Allocation Related Chapter: ABC.
C Functions Three major differences between C and Java functions: –Functions are stand-alone entities, not part of objects they can be defined in a file.
CPS4200 Unix Systems Programming Chapter 2. Programs, Processes and Threads A program is a prepared sequence of instructions to accomplish a defined task.
1 Functions  A function is a named, independent section of C++ code that performs a specific task and optionally returns a value to the calling program.
Variable Argument Lists CS 112 (slides from Marc Lihan)
USER DEFINED FUNCTIONS Computer Programming Asst. Prof. Dr. Choopan Rattanapoka and Asst. Prof. Dr. Suphot Chunwiphat.
Functions: Part 2 of /11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park 1.
 2007 Pearson Education, Inc. All rights reserved C Arrays.
 2008 Pearson Education, Inc. All rights reserved. 1 Arrays and Vectors.
2/23/2016Course material created by D. Woit 1 CPS 393 Introduction to Unix and C START OF WEEK 9 (C-3)
CS 1704 Introduction to Data Structures and Software Engineering.
Functions, Part 1 of 3 Topics  Using Predefined Functions  Programmer-Defined Functions  Using Input Parameters  Function Header Comments Reading 
C Tutorial - Pointers CS 537 – Introduction to Operating Systems.
Chapter 1 slides1 What is C? A high-level language that is extremely useful for engineering computations. A computer language that has endured for almost.
Lecture 3: Getting Started & Input / Output (I/O)
User-Written Functions
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
Input/output.
CS1010 Discussion Group 11 Week 4 – Overview of C programming.
Functions, Part 2 of 2 Topics Functions That Return a Value
C Programming Tutorial – Part I
Chapter 2 Overview of C.
Programmazione I a.a. 2017/2018.
2008/11/10: Lecture 16 CMSC 104, Section 0101 John Y. Park
2011/11/20: Lecture 15 CMSC 104, Section 4 Richard Chang
Computer Science 210 Computer Organization
Computer Science 210 Computer Organization
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
C Arrays.
Functions, Part 1 of 3 Topics Using Predefined Functions
Functions, Part 2 of 3 Topics Functions That Return a Value
Miscellaneous functions
Introduction to C Topics Compilation Using the gcc Compiler
Introduction to C Topics Compilation Using the gcc Compiler
Functions, Part 1 of 3 Topics Using Predefined Functions
Arrays.
Chapter 11 Programming in C
Functions, Part 1 of 3 Topics Using Predefined Functions
2008/11/05: Lecture 15 CMSC 104, Section 0101 John Y. Park
Functions, Part 2 of 3 Topics Functions That Return a Value
Functions, Part 2 of 3 Topics Functions That Return a Value
ICS103: Programming in C 6: Pointers and Modular Programming
Presentation transcript:

Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building blocks of C programs Functions must be declared above their use in a source file, or enter a prototype. Example: float foo(int n, char s) { Instructions } Return type to left of name –float is the return type –Enter: void if none –If non-void, return needed (JLJ) Example: return 3.2; Argument list within () –argument name, type, order –formal arguments (parameters) –Passed by value A call –int m=5;foo(m, 'a'); –m and 'a' are actual arguments Prototype: float foo(int, char);

Direct and Indirect Addresses Pointers: memory address pointing the data –Java: All objects are pointers Java hides pointers from the programmer –C Objects may or may not be pointers The programmer has control but must be very careful Defining pointers –Direct addressing (JLJ): int n; n = 10; –Indirect addressing: int *np; *np = 10; n np

Example Swapping values Does Nothing – Why? Function void swap(int x,int y) { int temp = x; x = y; y = temp; } Call to swap function int a=5, b = 10; swap(a, b); This one works Function swap(int *x, int *y) { int temp = *x; *x = *y; *y = temp; } Call to swap function int a=5, b = 10; swap(&a, &b); Note: Use direct addressing if not changing a parameter value Note: Use indirect addressing if changing a parameter value

Passing Pointers Nested function pass a pointer to a nested function Example: void foo1(int *a) { *a = 5; } void foo2(int *n) { foo1(n); } void main(int argc, char *argv[]) { int m=3; foo2(&m); printf("m = %d", m); } Notes –&m means address of m (convert direct to indirect addressing) –foo2 does not change n, so simply passes the pointer to foo1 –foo1 stores through the pointer indirectly –the printf statement prints a 5

Variable number of arguments #include double average ( int num,... ) // The … must be last { double sum = 0; int x; va_list args; va_start ( args, num ); for ( x = 0; x < num; x++ ) sum += va_arg( args, double ); va_end ( arguments ); return sum/num; } Example calls: printf( "%f\n", average ( 3, 12.2, 22.3, 4.5 ) ); printf( "%f\n", average ( 5, 3.3, 2.2, 1.1, 5.5, 3.3 ) );

Pass a function to a function Quick sort function prototype from the C library void qsort(void *base, size_t nmemb, size_t size, int(*compare)(const void *, const void *)); Example function for comparing elements #include int int_sorter( const void *first, const void *second ) { return (*(int*)first – *(int*)second); } Sample Call: qsort( array, 10, sizeof( int ), int_sorter );

Inputting from stdin (standard input) Use the scanf function int scanf(template, arg1, arg2, … ) Description –The template string is like that of printf –Reads possibly multiple values –Returns the number of successful reads –The arguments are addresses of variables –Example: int n; scanf("%d", &n); Note: "bob" entered is invalid and scanf returns zero –Example: scanf("%d %d", &i, &j); Note: scanf ignores whitespace. Non-whitespace characters in the template string must match exactly

Input Example (float) # include int main(int argc, char *argv[]) {float v; printf("Enter a value: "); while (scanf("%f", &v) != 1) { printf("Error, try again: "); scanf(“%*s");} Notes 1.scanf(%*s) rereads and discards erroneous data 2.The while loop tries until we have one successful read 3.Note the %f in the template for inputting a float value

Function Prototypes Normally you type the function above its use in a source file Sometimes prototypes can be useful –They can be declared below main –External source files can refer to them –Why? Because large it is reasonable in large projects Prototype: return foo(arg types) gcc can compile and link separately –Compile: gcc –c file creates file.o –Link: gcc main file.o function.o –o main

Header Files Contain information for multiple source files To access a header file: #include "header.h" /* in same folder */ #include /* in $INCLUDE folders */ Header files contain –Function prototypes –#define statements –Other preprocessor directives Common header files used by C programs –stdio.h (for stream I/O) –stdlib.h (for C run time library functions)

Exiting a Program Use the exit function –Need stdlib.h –Some implementations includes it in stdio.h Example: if (value<0) exit(1); elseexit(0); Note: exit(0) is a good return, exit(≠0) indicates an error. In UNIX, the value is returned to the shell so it can output an appropriate error message.