Programming Functions and File I/O
Summary Functions Definition Declaration Invocation Pass by value vs. pass by reference File I/O Reading Writing Static keyword Global vs. local variables 2
Functions Functions are subprograms that perform some operation How to write a program using functions? Conceptualize how a program can be broken into smaller parts Approach: Break down problem into simpler sub-problems Consider iteration and recursion Minimize transfer of state between functions Writing pseudocode first can help 3
Code Repetition Do NOT copy-paste code! Avoid at all cost! Greater probability of error Difficult to change Unreadable code Functions are the solution: Give some name to actions often repeated Set of instructions that can be invoked whenever is needed Eliminates code repetition Code is more readable, easy to understand and write 4
Function Definitions int main(void) / do stuff / return EXIT_SUCCESS; / success / Already seen some functions, including main()! Functions encapsulate some operation, so code can be re-used by others for example, the abs() or sqrt() function 5
Function Characteristics Reusable code code in sqrt() is reused often Encapsulated code implementation of sqrt() is hidden Can be stored in libraries sqrt() is a built-in function found in the math library Example: clear the screen and write a string Bad choice: repeat the code whenever it is needed Good choice: create a function and invoke it whenever is needed 6
Function Definition /* convert temperatures in Celsius to temperatures in Fahrenheit */ double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; Function definition ignores where it is invoked Receives a double and returns a double Input parameter: paramcel (temperature in Celsius) Returns a value that corresponds to the temperature in Fahrenheit 7
How to Use a Function? #include <stdio.h> double CtoF( double ); /******************************************************************* * Purpose: to convert temperature from Celsius to Fahrenheit *******************************************************************/ int main() double c, f; printf("enter the degree (in Celsius): "); scanf("%lf", &c); f = CtoF(c); printf("temperature (in Fahrenheit) is %lf\n", f); double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 8
Definitions Declaration: double CtoF( double ); Can be declared in.h Invocation (Call): Fahr = CtoF(Cel); In any place Definition: double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 9
Function Declaration Also called function prototype: return_type function_name (parameter_list) double CtoF(double) Declarations describe the function: Return type and function name Type and number of input parameters Doesn t need to have any input parameter or return any value void keyword! Functions in the same scope must have unique declarations 10
Already Known Functions Already known functions printf(), scanf(), sqrt(), sin() C Libraries have plenty of functions that can be used The return type must agree with the function return type WRONG: int val = sqrt(4.0); Input parameters must also agree in number and type to the defined function parameters WRONG: clock_t time = clock(20); 11
Function Invocation int main() f = CtoF(c); 1. Call copies argument c to parameter paramcel 2. Control transfers to function CtoF double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 12
Function Invocation int main() f = CtoF(c); 3. Expression in CtoF is evaluated 4. Value of expression is returned to main double CtoF ( double paramcel ) return paramcel*1.8 + 32.0; 13
Observations The parameter paramcel is only defined while the function is executing paramcel cannot be used outside the function The name of the parameter does not need to be the same as the name of the argument However, types must agree 14
Variable Scopes Scope Where a variable is known to exist No variable is known outside of the curly braces (block) that contain it, even if the same name is used! Variables declared inside a function: Called local variables Only know in the function Can only be manipulated inside the function Input parameters Are local variables Initialized with the value (copy) of the actual parameter In different functions a variable with the same name can be defined 15
Functions: Example #include <stdio.h> double GetTemperature(); double CelsiusToFahrenheit( double ); void DisplayResult( double, double ); int main() double TempC, TempF; // Temperature in degrees Celsius // Temperature in degrees Fahrenheit TempC = GetTemperature(); TempF = CelsiusToFahrenheit(TempC); DisplayResult(TempC, TempF); return 0; 16
Functions: Example (cont) double GetTemperature() double Temp; printf("\nplease enter a temperature in degrees Celsius: "); scanf("%lf", &Temp); return Temp; double CelsiusToFahrenheit(double Temp) return (Temp * 1.8 + 32.0); void DisplayResult(double CTemp, double FTemp) printf("original: %5.2f C\n", CTemp); printf("equivalent: %5.2f F\n", FTemp); return; 17
Pass by Value A copy of the argument s value is passed to the called function Changes to the copy do not affect the original variable s value in the caller Disadvantage: when a large data item is an argument, copying data may take considerable resources (execution time and memory) 18
Example: Pass by Value /* C function using pass by value */ void transform( int x ) x = 19; /* Test function for passing by value */ int main() int z = 15; transform( z ); printf("z is now %d\n", z); return 0; 19
Pass by Reference Called function can access and modify the caller s argument data directly Pass-by-reference advantage: good for performance reasons, because reduces the pass-by-value computational and memory overhead Pass-by-reference should be used with care: the called function can corrupt the caller s data Parameter name in the body of the called function actually refers to the original variable in the calling function Reference parameter pass the address (using the & operator) of the variable to be modified & placed after the parameter when the function is invoked 20
Pass by Reference Passing parameters by reference: In the function declaration always use * * declares a reference for a variable: can by any type! Allows to change the content of the variable referred by the function parameter Parameter usage f(int x) x = 12; // changes to variable x: no impact outside the function f(int *x) *x = 12; // changes of variable referred by x: impact outside the function 21
Pass by Reference int val = 10; MyFun(&val); printf( %d,val); void MyFun(int *param) *param = 27; Name Address Value val 0xeffffa90 10 param 0xefffea88 0xefffa90 22
Example: Pass by Reference /* C function using pass by reference */ void transform( int *x ) *x = 19; /* Test function for passing by reference */ int main() int z = 15; transform( &z ); printf("z is now %d\n", z); return 0; 23
Recursion Pseudo-code for the computation factorial if n == 0 then result = 1 else result = n * factorial(n 1) 5! = 5 * 4 * 3 * 2 * 1 = 5 * 4! Recursive call: Function contains an invocation of itself int Factorial(int n) if(n == 0) Base Case: Never Forget! May lead to return 1; infinite recursion else return n * Factorial(n-1); 24
File I/O File: sequence of characters or binary data on disk File I/O always involves three steps: Open the file (fopen) Read or write from/to the file (e.g. fgets/fputs) Close the file (fclose) 25
File I/O: fopen C allows to read data from text/binary files using fopen() FILE* fopen(char name[], char mode[]); FILE is an abstract data structure which holds information about a file Name is the location of the file on the disk (can be anywhere) Mode defines how the file is opened: can be "r"(read-only),"w"(writeonly),"a"(append) among other options fopen returns a pointer to the file stream (FILE *) if the file exists or NULL otherwise stdin, stdout are standard input and output FILE* datatypes stderr corresponds to the standard error output (different from stdout) 26
File I/O: fclose int fclose (FILE* fp) Closes the file stream and releases OS resources Automatically called on all open files when program ends 27
Modes of fopen Write, Read and Append File must exist when opened in read mode If file exists in write mode its contents will be overwritten Append doesn t overwrite contents as in the write mode r - open a text file for reading w - truncate to zero length or create a text file for writing a - (append) open or create text file for writing at end-of-file rb - open binary file for reading wb - truncate to zero length or create a binary file for writing ab - (append) open or create binary file for writing at end-of-file 28
Example: Opening and Closing a File #include <stdio.h> #include <stdlib.h> int main () FILE *inputfp, *outputfp; char outputfile[] = "my_output.txt"; Opening a file for reading inputfp = fopen("my_input.txt", "r"); if (inputfp == NULL) printf("can't open input file my_input.txt!\n"); exit(exit_failure); outputfp = fopen(outputfile, "w"); if (outputfp == NULL) printf("can't open output file %s!\n", outputfile); exit(exit_failure); fclose(inputfp); fclose(outputfp); return EXIT_SUCCESS; Opening a file for writing Closing files! 29
File I/O: getc and fgets int getc(file* fp) Reads a single character from the file stream Returns the character read or EOF on error/end of file char[] fgets (char line [], int maxlen, FILE* fp) Reads a single line (up to maxlen characters) from the input file stream (including line break) Returns a pointer to the character array that stores the line (read-only) Returns NULL if end of stream or in case of error 30
File I/O: putc, fputs, fscanf, fprintf int putc( int c,file* fp) Writes a single character c to the output stream Returns the character written or EOF on error int fputs (char line [], FILE* fp) Writes a single line to the output stream Returns zero on success, EOF otherwise int fscanf (FILE* fp, char format [],.) Similar to scanf and sscanf Reads items from input stream fp int fprintf(file* fp, char format [],.) Similar to printf 31
Non-Persistent Storage If a variable declaration is executed multiple times, is new memory for the variable allocated each time? For normal variables yes int f ( void ) int temporary;... Each time f() is called, new memory is allocated for temporary Each time f() terminates, the memory is deallocated that instance of temporary disappears Allocation and deallocation takes time and effort 32
Persistent Storage: static If a variable declaration is executed multiple times, is new memory for the variable allocated each time? For static variables the answer is no! Memory is allocated once at the first use of the variable and then reused int f ( void ) static int persistent;... The first time f() is called, new memory is allocated for persistent Every next call to f() reuses that memory potentially using values that earlier calls to f() left behind 33
Why Use Static Storage? Avoid overhead of allocating, initializing, deallocating memory with each function call Maintain some state information over multiple calls to the function int f( void ) /* count number of times f has been called */ static int num_calls = 0;... num_calls++; return; 34
Global vs Local Variables Variables declared inside each function (including main) are local variables Even if the same name is used! Memory reserved for each variable is deallocated at the end of the function Global variables: variables external to every function that is recognized by every function If a function changes the global variable contents, its stay allocated and accessible even if the function ends Global variable declaration statements should appear before any function definition Right at the beginning of the file 35
Example: Global Variables // declare global variable int g_nmode = 1; void dosomething() g_nmode = 2; int main() g_nmode = 1; dosomething(); // Programmer expects g_nmode to be 1 // But dosomething changed it to 2! if (g_nmode == 1) printf("no threat detected.\n ); else printf("launching nuclear missiles... ); 36 return 0;
Warning: Global Variables! An alteration in the value of a global variable within a given function may have impact over all other functions Global variable may change unexpectedly, resulting in a subtle programming error which can be extremely difficult to detect Conclusion: AVOID ITS USE!!! 37
To Review Marques de Sá Capítulo 4 Capítulo 10 (até ao 10.4) Damas Capítulo 5 Capítulo 10 Kernighan and Ritchie Chapter 4 Chapter 7 38