PROGRAMMAZIONE I A.A. 2017/2018

Similar documents
PROGRAMMAZIONE I A.A. 2017/2018

M1-R4: Programing and Problem Solving using C (JAN 2019)

Computer Science & Information Technology (CS) Rank under AIR 100. Examination Oriented Theory, Practice Set Key concepts, Analysis & Summary

PROGRAMMAZIONE I A.A. 2017/2018

BIL 104E Introduction to Scientific and Engineering Computing. Lecture 14

PROGRAMMAZIONE I A.A. 2018/2019

CS 326 Operating Systems C Programming. Greg Benson Department of Computer Science University of San Francisco

CSE 2421: Systems I Low-Level Programming and Computer Organization. Functions. Presentation C. Predefined Functions

Unit 7. Functions. Need of User Defined Functions

Programming in C. What is C?... What is C?

Programming in C UVic SEng 265

B.V. Patel Institute of Business Management, Computer & Information Technology, Uka Tarsadia University

CS240: Programming in C

Programming in C. What is C?... What is C?

AN OVERVIEW OF C, PART 3. CSE 130: Introduction to Programming in C Stony Brook University

C Programming Review CSC 4320/6320

Arrays and Pointers (part 2) Be extra careful with pointers!

From Java to C. Thanks to Randal E. Bryant and David R. O'Hallaron (Carnegie-Mellon University) for providing the basis for these slides

3.Constructors and Destructors. Develop cpp program to implement constructor and destructor.

Hello, World! in C. Johann Myrkraverk Oskarsson October 23, The Quintessential Example Program 1. I Printing Text 2. II The Main Function 3

Creating, Compiling and Executing

Outline. Lecture 1 C primer What we will cover. If-statements and blocks in Python and C. Operators in Python and C

Review of the C Programming Language for Principles of Operating Systems

Subject: Fundamental of Computer Programming 2068

PROGRAMMAZIONE I A.A. 2017/2018

Structured Programming. Functions and Structured Programming. Functions. Variables

Arrays and Pointers (part 2) Be extra careful with pointers!

PROGRAMMAZIONE I A.A. 2017/2018

Array Initialization

Lecture 03 Bits, Bytes and Data Types

Functions in C C Programming and Software Tools

CS240: Programming in C

Chapter 6: User-Defined Functions. Objectives (cont d.) Objectives. Introduction. Predefined Functions 12/2/2016

/* EXAMPLE 1 */ #include<stdio.h> int main() { float i=10, *j; void *k; k=&i; j=k; printf("%f\n", *j);

Personal SE. Functions, Arrays, Strings & Command Line Arguments

PROGRAMMAZIONE I A.A. 2017/2018

Memory Allocation in C

Arrays and Pointers. CSE 2031 Fall November 11, 2013

COMP 2355 Introduction to Systems Programming

unsigned char memory[] STACK ¼ 0x xC of address space globals function KERNEL code local variables

Lecture 04 FUNCTIONS AND ARRAYS

Functions in C C Programming and Software Tools. N.C. State Department of Computer Science

Review of the C Programming Language

Chapter 7 Functions. Now consider a more advanced example:

CS 0449 Sample Midterm

CS 261 Fall C Introduction. Variables, Memory Model, Pointers, and Debugging. Mike Lam, Professor

CSE 230 Intermediate Programming in C and C++ Functions

Arrays and Pointers. Arrays. Arrays: Example. Arrays: Definition and Access. Arrays Stored in Memory. Initialization. EECS 2031 Fall 2014.

Outline. Computer programming. Debugging. What is it. Debugging. Hints. Debugging

CSC 1600 Memory Layout for Unix Processes"

C-LANGUAGE CURRICULAM

PROGRAMMAZIONE I A.A. 2017/2018

Lecture 9 - C Functions

CSE 374 Programming Concepts & Tools

CSci 4061 Introduction to Operating Systems. Programs in C/Unix

IMPORTANT QUESTIONS IN C FOR THE INTERVIEW

CS2141 Software Development using C/C++ C++ Basics

Final CSE 131B Spring 2004

Variables Data types Variable I/O. C introduction. Variables. Variables 1 / 14

Name :. Roll No. :... Invigilator s Signature : INTRODUCTION TO PROGRAMMING. Time Allotted : 3 Hours Full Marks : 70

Dynamic memory allocation

Introduction to Programming (Java) 4/12

CS Programming In C

Memory. What is memory? How is memory organized? Storage for variables, data, code etc. Text (Code) Data (Constants) BSS (Global and static variables)

Lecture 12 CSE July Today we ll cover the things that you still don t know that you need to know in order to do the assignment.

Fundamentals of Programming Session 12

A3-R3: PROGRAMMING AND PROBLEM SOLVING THROUGH 'C' LANGUAGE

Functions. Systems Programming Concepts

Functions. Lab 4. Introduction: A function : is a collection of statements that are grouped together to perform an operation.

Unit 3 Functions. 1 What is user defined function? Explain with example. Define the syntax of function in C.

Flow Control. CSC215 Lecture

Binghamton University. CS-211 Fall Syntax. What the Compiler needs to understand your program

Function a block of statements grouped together, to perform some specific task

C & Data Structures syllabus

C Introduction. Comparison w/ Java, Memory Model, and Pointers

Functions. Cedric Saule

#include <stdio.h> int main() { char s[] = Hsjodi, *p; for (p = s + 5; p >= s; p--) --*p; puts(s); return 0;

Functions. Computer System and programming in C Prentice Hall, Inc. All rights reserved.

Understanding Pointers

Functions. (transfer of parameters, returned values, recursion, function pointers).

Programming in C. Pointers and Arrays

Chapter 11 Introduction to Programming in C

Chapter 14 - Advanced C Topics

Ricardo Rocha. Department of Computer Science Faculty of Sciences University of Porto

Implementing Subroutines. Outline [1]

Faculty of Engineering Computer Engineering Department Islamic University of Gaza C++ Programming Language Lab # 6 Functions

Dynamic memory allocation (malloc)

& Technology. G) Functions. void. Argument2, Example: (Argument1, Syllabus for 1. 1 What. has a unique. 2) Function name. passed to.

COMP26120: Algorithms and Imperative Programming. Lecture 5: Program structuring, Java vs. C, and common mistakes

Lecture 5: Methods CS2301

CS313D: ADVANCED PROGRAMMING LANGUAGE

Binghamton University. CS-211 Fall Functions. The Basis of C

Overview (1A) Young Won Lim 9/14/17

CSCI-243 Exam 1 Review February 22, 2015 Presented by the RIT Computer Science Community

15 FUNCTIONS IN C 15.1 INTRODUCTION

A Fast Review of C Essentials Part I

C Functions. 5.2 Program Modules in C

CSE 303: Concepts and Tools for Software Development

C: Arrays, and strings. Department of Computer Science College of Engineering Boise State University. September 11, /16

Lab Exam 1 D [1 mark] Give an example of a sample input which would make the function

Transcription:

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, ); Both valid declarations type function_name (type, type, );

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 Function prototype scope Block 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); 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." ); else { puts( "The command line arguments:" ); for ( int i = 1; i < argc; ++i ) puts( argv[i] ); // Print each argument on // a separate line.

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

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 #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