Programmazione I a.a. 2017/2018.

Slides:



Advertisements
Similar presentations
Chapter 7 Process Environment Chien-Chung Shen CIS, UD
Advertisements

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.
1 Review of Chapter 3--- Flow of Control  How to specify conditions?  Relational, Equality and Logical Operators  Statements  Statements: compound.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. Chapter 5 - Functions Outline 5.1Introduction 5.2Program.
COMP 110 Introduction to Programming Mr. Joshua Stough October 8, 2007.
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.
CS 201 Functions Debzani Deb.
 2003 Prentice Hall, Inc. All rights reserved. 1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined.
1 Functions Modules: functions and classes Programs use new and “prepackaged” modules –New: programmer-defined functions, classes –Prepackaged: from the.
Introduction to Methods
FunctionsFunctions Systems Programming Concepts. Functions   Simple Function Example   Function Prototype and Declaration   Math Library 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.
© Copyright 1992–2004 by Deitel & Associates, Inc. and Pearson Education Inc. All Rights Reserved. C How To Program - 4th edition Deitels Class 05 University.
Digital Computer Concept and Practice Copyright ©2012 by Jaejin Lee C Language Part 2.
Chapter 06 (Part I) Functions and an Introduction to Recursion.
Chapter 6: User-Defined Functions
C++ Programming: From Problem Analysis to Program Design, Fifth Edition, Fifth Edition Chapter 7: User-Defined Functions II.
Functions Kernighan/Ritchie: Kelley/Pohl: Chapter 4 Chapter 5.
 2005 Pearson Education, Inc. All rights reserved. 1 Methods Called functions or procedures in other languages Modularize programs by separating its tasks.
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.
Functions Illustration of: Pass by value, reference Scope Allocation Reference: See your CS115/215 textbook.
Functions Math library functions Function definition Function invocation Argument passing Scope of an variable Programming 1 DCT 1033.
1 MORE ON MODULAR DESIGN: MODULE COMMUNICATIONS. 2 WHEN A FUNCTION IS INVOKED, MEMORY IS ALLOCATED LOCALLY FOR THE FORMAL PARAMETERS AND THE VALUE OF.
Functions in C++ Top Down Design with Functions. Top-down Design Big picture first broken down into smaller pieces.
Chapter 7 - Functions. Functions u Code group that performs single task u Specification refers to what goes into and out of function u Design refers to.
Learners Support Publications Constructors and Destructors.
Objectives: How to define and call functions. Function declarations and how they differ from function definitions. How arguments are passed to functions.
Chapter 7 Process Environment Chien-Chung Shen CIS/UD
 Pearson Education, Inc. All rights reserved Methods: A Deeper Look.
BIL 104E Introduction to Scientific and Engineering Computing Lecture 4.
Constructors and Destructors
Chapter 9: Value-Returning Functions
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
User-Written Functions
Chapter 6 - Functions modular programming general function format
The Machine Model Memory
Chapter 7: User-Defined Functions II
Chapter 2 - Introduction to C Programming
Suppose we want to print out the word MISSISSIPPI in big letters.
Command Line Arguments
Command Line Arguments
Functions and Structured Programming
FUNCTIONS IN C++.
Programmazione I a.a. 2017/2018.
CS1061 C Prgramming Lecture 11: Functions
Chapter 2 - Introduction to C Programming
Instructor: Ioannis A. Vetsikas
User-Defined Functions
11/10/2018.
Chapter 5 - Functions Outline 5.1 Introduction
Chapter 3 Introduction to Classes, Objects Methods and Strings
User Defined Functions
Chapter 14 - Advanced C Topics
Chapter 6 Methods: A Deeper Look
6 Chapter Functions.
Functions.
Constructors and Destructors
Classes and Objects.
Chapter 9: Value-Returning Functions
Predefined Functions Revisited
Classes, Objects and Methods
Programming Languages and Paradigms
Functions Students should understand the concept and basic mechanics of the function call/return pattern from CS 1114/2114, but some will not. A function.
Presentation transcript:

Programmazione I a.a. 2017/2018

FUNCTIONS

Introduction and main All the instructions of a C program are contained in functions. C is a procedural language Each function performs a certain task A special function name is main( ): the function with this name is the first one to run when the program starts. The first command executed in your program is the first command in main (top to bottom) All other functions are subroutines of the main( ) function can have any names you wish. Every function is defined exactly once. A program can declare and call a function as many times as necessary.

Function definition The definition of a function consists of a function head (or the declarator), and a function block. The function head specifies the name of the function, the type of its return value, and the types and names of its parameters, if any. The statements in the function block specify what the function does. type function_name (type parameter_name1, type parameter_name2,…) { //statements; }

Function return Always write the return-value type It is int if not specified

Function declaration By declaring a function before using it, you inform the compiler of its type: in other words, a declaration describes a function’s interface A declaration defines the type of a function The number and types of its parameters The type of what returned The identifiers of the parameters in a function declaration are optional. If you include the names, their scope ends with the prototype itself type function_name (type parameter_name1, type parameter_name2,…); type function_name (type, type,…); Both valid declarations

Identifier scope 2 Block scope: identifiers declared within a block have block scope. You can use such an identifier only from its declaration to the end of the smallest block containing that declaration. The smallest containing block is often, but not necessarily, the body of a function definition. In C11, declarations do not have to be placed before all statements in a function block. The parameter names in the head of a function definition also have block scope, and are valid within the corresponding function block. Function prototype scope: The parameter names in a function prototype have function prototype scope. Because these parameter names are not significant outside the prototype itself, they are meaningful only as comments, and can also be omitted.

Identifier scope 3 Function scope: the scope of a label is always the function block in which the label occurs, even if it is placed within nested blocks. In other words, you can use a goto statement to jump to a label from any point within the same function that contains the label. (Jumping into nested blocks is not a good idea, though). The scope of an identifier generally begins after its declaration. However, the type names, or tags, of structure, union, and enumeration types and the names of enumeration constants are an exception to this rule: their scope begins immediately after their appearance in the declaration, so that they can be referenced again in the declaration itself.

Example 1 int p; int fun1 (int q); int fun2 (int r) { int s = r + 3; while( r != s) r--; } File scope Block scope Function prototype scope p, fun1, fun2 q r,s

Function parameters The parameters of a function are ordinary local variables. The program creates them, and initializes them with the values of the corresponding arguments, when a function call occurs. Their scope is the function block (block scope). long double factorial( unsigned int n ) { long double f = 1; while ( n > 1 ) f *= n--; return f; }

Declaration and definition A function definition is also a function declaration int fun2 (int); int main() { int a= 5; a= fun2(a); } int fun2 (int r) { int s = r + 5; while( r != s) r--; return r; int fun2 (int r) { int s = r + 5; while( r != s) r--; return r; } int main() { int a= 5; //commands a= fun2(a); =

So Before calling (using) a function you need to declare it You can declare all the functions at the top of the file, and define them in any order below in the same file Otherwise you can avoid declaring function at the top, but you need to define them before they the are called A function needs also to be defined, otherwise you do not know hat to do when it is called In the same file, you cannot have two definitions of functions with the same header and identifier (name)

example int fun1 (int); int fun2 (int r) { int fun2 (int); int main() { int a= 5; a= fun2(a); } int fun1(int q) { return (fun2(q)+1); int fun2 (int r) { int s = r + 5; while( r != s) r--; return r; int fun2 (int r) { int s = r + 5; while( r != s) r--; return r; } int main() { int a= 5; a= fun2(a); int fun1(int q) { return (fun2(q)+1);

example int fun1 (int); int main() { int a= 5; a= fun2(a); } int fun1 (int q) { return (fun2(q)+1); int fun2 (int r) { int s = r + 5; while( r != s) r--; return r; int fun1 (int); int fun2 (int); int main() { int a= 5; a= fun2(a); } int fun1 (int q) { return (fun2(q)+1); int fun2 (int r) { int s = r + 5; while( r != s) r--; return r;

return The return statement ends execution of the current function, and jumps back to where the function was called : return [expression]; expression is evaluated and the result is given to the caller as the value of the function call. This return value is converted to the function’s return type, if necessary. A function can contain any number of return statements Return is an unconditional jump statement (as goto)

example // Return the smaller of two integer arguments. int min( int a, int b ) { if ( a < b ) return a; else return b; } int main() int a= 5; int b= 6; int c= min(a ,b); printf(“%d”, c); 5

Return (2) A return statement with no expression can only be used in a function of type void. In fact, such functions do not need to have a return statement at all. If no return statement is encountered in a function, the program flow returns to the caller when the end of the function block is reached.

MAIN

Main() function You can define the main( ) function in one of the following two forms: int main( void ) { /* ... */ } A function with no parameters, returning int int main( int argc, char *argv[] ) { /* ... */ } A function with two parameters whose types are int and char **, returning int

Parameters of main() The parameters argc and argv (which you may give other names if you wish) represent your program’s command-line arguments. This is how they work: argc (short for “argument count”) is either 0 or the number of string tokens in the command line that started the program. The name of the program itself is included in this count. argv (short for “arguments vector”) is an array of pointers to char that point to the individual string tokens received on the command line: The number of elements in this array is one more than the value of argc; the last element, argv[argc], is always a null pointer. If argc is greater than 0, then the first string, argv[0], contains the name by which the program was invoked. If the execution environment does not supply the program name, the string is empty. If argc is greater than 1, then the strings argv[1] through argv[argc - 1] contain the program’s command line arguments.

A classical example #include <stdio.h> int main( int argc, char *argv[] ) { if ( argc == 0 ) puts( "No command line available." ); else { printf( "The program now running: %s\n", argv[0] ); // Print the name of the // program. if ( argc == 1 ) puts( "No arguments received on the command line." ); puts( "The command line arguments:" ); for ( int i = 1; i < argc; ++i ) // Print each argument on // a separate line. puts( argv[i] ); }

Output for the example Suppose we run the program on a Unix system by entering the following command line: $ ./args one two "and three" The output is then as follows: The program now running: ./args The command line arguments: one two and three

Return of main The value returned by main is a value that is passed The return value for main should indicate how the program exited. Normal exit is generally represented by a 0 return value from main. Abnormal termination is usually signalled by a non-zero return The OS returns this value to the process which called the executed program (e.g., the shell)

HOW FUNCTIONS ARE EXECUTED

Returning from a function If the program reaches a return statement or the closing brace } of the function block, execution of the function ends, and the program jumps back to the calling function. If the program “falls off the end” of the function by reaching the closing brace, the value returned to the caller is undefined. For this reason, you must use a return statement to stop any function that does not have the type void. The value of the return expression is returned to the calling function.

Call a function The instruction to execute a function—the function call— consists of the function’s name and the operator ( ) For example, the following statement calls the function maximum( ) to compute the maximum of two numbers maximum( a, b); The program first allocates storage space for the parameters, then copies the argument values to the corresponding locations. Then the program jumps to the beginning of the function, and execution of the function begins with first variable definition or statement in the function block.

Wrong p 3 i and j are passed by value! q #include <stdio.h> 5 Memory p q 3 i and j are passed by value! #include <stdio.h> int sum(int p, int q) { int r= 0; r= p + q; return r; } int main( void ) { int i =3, j =5, int s= 0; s= sum(i, j); printf(”%d\n”, s); return 0; 5 r 8 3 5 i j s 8 8

Variable Allocation Memory allocation means that part of the memory is reserved, for instance for a variable Automatic variable is a local variable which is allocated and deallocated automatically when program flow enters and leaves the variable's scope By memory deallocation we mean that part of the memory is no longer reserved, for that variable

OVERLOADING OF FUNCTIONS

NOT POSSIBLE IN C! Function overloading is a feature of a programming language that allows one to have many functions with same name but with different signatures (parameters’ type and return type) This feature is present in most of the Object Oriented Languages such as C++ and Java But C doesn’t support this feature To overload a function, in C++ you an define it several times, each uniquely identified by the type of the arguments it accepts; return type is not considered

example MacBook-Francesco:ProgrammI francescosantini$ gcc esempio.c #include<stdio.h> int min(int a, int b) { return ( x < y ? x : y);} float min(float a, float b) { return ( x < y ? x : y); } int main( ) { int a= min(4, 1); float b= min(4.56F, 1.23F); MacBook-Francesco:ProgrammI francescosantini$ gcc esempio.c esempio.c:8:7: error: conflicting types for 'min' float min(float a, float b) { ^ MacBook-Francesco:ProgrammI francescosantini$ g++ esempio.c