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.

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

Lecture 20 Arrays and Strings
What is a pointer? First of all, it is a variable, just like other variables you studied So it has type, storage etc. Difference: it can only store the.
Functions in C++. Functions  Groups a number of program statements into a unit & gives it a name.  Is a complete and independent program.  Divides.
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II
C++ Programming: Program Design Including Data Structures, Third Edition Chapter 7: User-Defined Functions II.
Chapter 7: User-Defined Functions II Instructor: Mohammad Mojaddam.
Functions Definition: Instruction block called by name Good design: Each function should perform one task and do it well Functions are the basic building.
ספטמבר 04Copyright Meir Kalech1 C programming Language Chapter 3: Functions.
Chapter 6. 2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single Value Pass by Reference Variable Scope.
1 Functions and Structured Programming. 2 Structured Programming Structured programming is a problem-solving strategy and a programming methodology. –The.
C Lecture Notes Functions (Cont...). C Lecture Notes 5.8Calling Functions: Call by Value and Call by Reference Used when invoking functions Call by value.
COMP1170 Midterm Preparation (March 17 th 2009) Acknowledgment The notes are adapted from those provided by Deitel & Associates, Inc. and Pearson Education.
Chapter 3: Introduction to C Programming Language C development environment A simple program example Characters and tokens Structure of a C program –comment.
Chapter 6: Function. Scope of Variable A scope is a region of the program and broadly speaking there are three places, where variables can be declared:
Lecture No: 16. The scanf() function In C programming language, the scanf() function is used to read information from standard input device (keyboard).
Review of C++ Programming Part II Sheng-Fang Huang.
Functions in C. Function Terminology Identifier scope Function declaration, definition, and use Parameters and arguments Parameter order, number, and.
 Introduction Introduction  Types of Function Types of Function  Library function Library function  User defined function User defined function 
Chapter 7 Functions.
Operator Precedence First the contents of all parentheses are evaluated beginning with the innermost set of parenthesis. Second all multiplications, divisions,
C Functions Programmer-defined functions – Functions written by the programmer to define specific tasks. Functions are invoked by a function call. The.
18-2 Understand “Scope” of an Identifier Know the Storage Classes of variables and functions Related Chapter: ABC 5.10, 5.11.
A First Book of C++: From Here To There, Third Edition2 Objectives You should be able to describe: Function and Parameter Declarations Returning a Single.
MAHENDRAN CHAPTER 6. Session Objectives Explain Type of Functions Discuss category of Functions Declaration & Prototypes Explain User Defined Functions.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
C++ function call by value The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Chapter 0.2 – Pointers and Memory. Type Specifiers  const  may be initialised but not used in any subsequent assignment  common and useful  volatile.
PASSING VALUE TO A FUNCTION # CALL BY VALUECALL BY VALUE # CALL BY REFERENCECALL BY REFERENCE STORAGE CLASS # AUTOAUTO # EXTERNALEXTERNAL # STATICSTATIC.
Learners Support Publications Classes and Objects.
Functions CIS Feb-06. Summary Slide Using Functions Mathematical Functions Misc. Functions Naming Conventions Writing Functions –Function Prototype.
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.
Learners Support Publications Functions in C++
Lecture 22: Reviews for Exam 2. Functions Arrays Pointers Strings C Files.
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.
Dale Roberts CSCI 230 Functions Scope, Parameter Passing, Storage Specifiers Department of Computer and Information Science, School of Science, IUPUI Dale.
Engineering H192 - Computer Programming Gateway Engineering Education Coalition Lect 12P. 1Winter Quarter User-Written Functions Lecture 12.
FUNCTIONS. Funtions  The heart of effective problem solving is problem decomposition.  breaking a problem into small, manageable pieces  In C, the.
Functions in C CSE 2451 Rong Shi. Functions Why use functions? – Reusability Same operation, different data – Abstraction Only need to know how to call.
KIC/Computer Programming & Problem Solving 1.  Header Files  Storage Classes  Scope Rules  Recursion Outline KIC/Computer Programming & Problem Solving.
CHAPTER 10 ARRAYS AND FUNCTIONS Prepared by: Lec. Ghader Kurdi.
Function Overloading and References
Chapter 5 Modular Design and Function C Programming for Scientists & Engineers with Applications by Reddy & Ziegler.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
EEL 3801 C++ as an Enhancement of C. EEL 3801 – Lotzi Bölöni Comments  Can be done with // at the start of the commented line.  The end-of-line terminates.
Senem Kumova Metin // CS115 // FUNCTIONS CHAPTER 5.
Functions Skill Area 314 Part B. Lecture Overview Functions Function Prototypes Function Definitions Local Variables Global Variables Default Parameters.
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 This week Basics of functions Stack frames Stack vs. Heap (brief intro) Calling conventions Storage classes vs. scope Library functions Overloading.
EKT120: Computer Programming
User-Written Functions
Chapter 7: User-Defined Functions II
C Functions -Continue…-.
A bit of C programming Lecture 3 Uli Raich.
Friend Class Friend Class A friend class can access private and protected members of other class in which it is declared as friend. It is sometimes useful.
FUNCTIONS In C++.
Functions and Structured Programming
Module 4 Functions – function definition and function prototype.
Command-Line Arguments
Programmazione I a.a. 2017/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Scope, Parameter Passing, Storage Specifiers
In C Programming Language
Functions Reasons Concepts Passing arguments to a function
CPS125.
Presentation transcript:

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.  A function definition consists of two aspects:  prototype  proper definition

2 Functions syntax is: return_type function_name ( type [parameterName]...);

3 Functions The proper definition of a function consists of the function header and its body Function definition syntax is: return_type function_name ( [type parameterName]...) { statements; }

4 Functions Function definition

5 Functions Parameters and Arguments There are three ways to pass data from one function to another: By value By address By reference

6 Functions #include void swap1 (int x, int y)// pass-by-value (objects) { printf("Function swap1\n" ); printf("Initial values: x=%d, y=%d\n ",x, y) ; int temp = x; x = y; y = temp; printf("Final values: x=%d y= %d\n ", x, y); }

7 Functions void swap2 (int *x, int *y)// pass-by-address (pointers) { printf("Function swap2\n "); printf("Initial values: *x=%d, *y=%d\n", *x, *y); int temp = *x; *x = *y; *y = temp; printf("Final values: *x=%d, *y=%d\n",*x, *y ); }

8 Functions void swap3 (int &x, int &y)// pass-by-reference { printf("Function swap3\n"); printf("Initial values: x=%d, y=%d\n", x, y) ; int temp = x; x = y; y = temp; printf("Final values: x=%d, y=%d ", x, y ); }

9 Functions void main(void) { int a, b; printf("a= "); scanf("%d", &a); printf("b= "); scanf(" %d ", &b); swap1( a, b); printf(“a= %d, b=%d\n“, a, b); swap2( &a, &b); printf(“a= %d, b=%d”, a, b ); swap3( a, b); printf(“a= %d, b=%d”, a, b ); }

10 Functions  Scope of variables:  Global  Local Scope  Global variables are dangerous because they are shared data  scope access (or resolution) operator :: (two semicolons) to access a global (or file duration) name even if it is hidden by a local redeclaration of that name.

11 Functions  Modifiers of memory location:  auto  register  static  extern

12 Functions  Command Line Arguments When a program is executed under an operating system (such as DOS or UNIX), it is able to pass zero or more arguments. These arguments appear after the program executable name and are separated by blanks. Because they appear on the same line as where operating system commands are issued, they are called command line arguments. Command line arguments are made available to a C++ program via the main function.

13 Functions The declaration of main looks like this: int main(int argc, char *argv[ ]); There are at least two arguments to main: argc and argv. The first of these is a count of the arguments supplied to the program and the second is an array of pointers to the strings which are those arguments—its type is (almost) ‘array of pointer to char’. These arguments are passed to the program by the host system's command line interpreter or job control language.

14 Functions #include int main (int argc, const char *argv[ ]) { double sum = 0; for (int i = 1; i < argc; ++i) sum += atof(argv[i]); printf(“ sum=%d\n”, sum ); return 0; }

15 Functions  Variable Number of Arguments It is sometimes desirable to have functions which take a variable number of arguments. The declaration is: tip_returned name_of_function(fix_parameters, …);

16 Functions #include int Menu (char *option1,...) { va_list args;// argument list char* option = option1; int count = 0, choice = 0; va_start(args, option1);// initialize args do { printf(“%d. %s \n”, ++count, option); } while ((option = va_arg(args, char*)) != 0); va_end(args);// clean up args printf("option? “); scanf(“%d”, &choice); return (choice > 0 && choice <= count) ? choice : 0; }

17 Functions The sample call int n = Menu( "Open file", "Close file", "Revert to saved file", "Delete file", "Quit application", 0); will produce the following output: 1. Open file 2. Close file 3. Revert to saved file 4. Delete file 5. Quit application option?

18 Functions  Recursion –A function can call itself. A function which calls itself is said to be recursive long fact (unsigned int n) { if (n<=1) return 1; else return n*fact(n-1); }

19 Functions  Inline Functions If a function is declared with the keyword inline, the compiler copies the code from the inline function directly into the calling function. If the function is called 10 times, the inline code is copied into the calling functions each of those 10 times. Effects: the execution speed increases size of executable program increases

20 Functions Example of inline function inline int Max (int a, int b) { return a > b ? a : b; }

21 Functions  Default Arguments #include void f (int i, int j = 25, float r = 2.5) { printf( "\n%d, %d, %f”, i, j, r); } void main() { f(3,5,1.5); (3,5); f(3); f(); // error, too few parameters ! }

22 Functions  Overloading Functions C++ enables to create more than one function with the same name. This is called function overloading (or polymorphism). The functions must differ in their parameter list. int func (int, int); int func (long, long); long func (long);

23 Functions /*overloading functions*/ #include int sum(int a,int b) { return a+b; } double sum(double a, double b) { return a+b;} char * sum(char *a, char *b) {return strcat(a,b);} void main() {printf( "42+17 = %d \n“, sum(42,17)); printf( " = %lf\n", sum(42.0,17.0)); printf( " C++ + is the best = %s“, sum("C++ ", "is the best !")); }

24 Functions  Function pointers  Function Pointers are pointers, i.e. variables, which point to the address of a function.  A running program gets a certain space in the main-memory. Both, the executable compiled program code and the used variables, are put inside this memory.  A function name is an address.

25 Functions #include void func1() {printf(“\ncall of function 1”);} void func2(int x) {printf(“\ncall of function 2”); printf(“\nx = %d”, x); } void main() { func1();//call of func1 func1;//address of func1 func2(5);//call of func2 func2;//address of func2 }

26 Functions Syntax of declaration of function pointers: type (* pointer_name)(parameter_list);  A function pointer always points to a function with a specific signature!  All functions, you want to use with the same function pointer, must have the same parameters and return-type!

27 Functions #include int comp1(char * s1, char *s2) {return s1[0] - s2[0]; } int comp2(char * s1, char *s2) {return strlen(s1) - strlen(s2); } void test(char* s1, char* s2, int(*p)(char*,char*)) {if (p(s1,s2)==0) printf("\nSirurule sunt identice“); else if (p(s1,s2)>0) printf("\nPrimul sir e mai mare“); else printf("\nAl doilea sir este mai mare“); }

28 Functions void main() { int (*p)(char*,char*); p=comp1; test("abc", "ABC", p); p=comp2; test("abc", "ABC", p); test("abc", "ABC", comp1); test("abc", "ABC", comp2); }