Functions Sagor Chandro Bakchy Assistant Professor 1 Functions Functions are block of code that can do any specific job Once a function code is written it can be executed many times Basically two types of functions: 1. Built-in function/Library function 2. User Defined function 2 Functions Compiler provides pre-written functions called user defined function Example: printf(), scanf(), malloc(), calloc(), pow(), sqrt() etc. C allows to define functions according to user need. These functions are known as user-defined functions. Example: Suppose, you need to create a circle and color it depending upon the radius and color. You can create two functions to solve this problem: createCircle() function color() function 3 Functions Components of user defined function 1. Return type 2. Function name 3. Parameter list with type 4. Function body 5. Return statement 4 Function’s Necessity Functions help us in reducing code redundancy. If functionality is performed at multiple places in software, then rather than writing the same code, again and again, we create a function and call it everywhere. This also helps in maintenance as we have to change at one place if we make future changes to the functionality. Functions make code modular. Consider a big file having many lines of code. It becomes really simple to read and use the code if the code is divided into functions. Functions provide abstraction. For example, we can use library functions without worrying about their internal working. 5 Parameter Passing to functions The parameters passed to function are called actual parameters. The parameters received by function are called formal parameters. 6 Parameter Passing to functions There are two most popular ways to pass parameters. Pass by Value/Call by Value: In this parameter passing method, values of actual parameters are copied to function’s formal parameters and the two types of parameters are stored in different memory locations. So any changes made inside functions are not reflected in actual parameters of caller. Pass by Reference/Call by Reference: Both actual and formal parameters refer to same locations, so any changes made inside the function are actually reflected in actual parameters of caller. Parameters are always passed by value in C. If we need to pass by reference it requires other coding. 7 Parameter Passing to functions 1) Every C program has a function called main() that is called by operating system when a user runs the program. 2) Every function has a return type. If a function doesn’t return any value, then void is used as a return type. Moreover, if the return type of the function is void, we still can use return statement in the body of function definition by not specifying any constant, variable, etc. with it, by only mentioning the ‘return;’ statement. 3) In C, functions can return any type except arrays and functions. We can get around this limitation by returning pointer to array or pointer to function. 8 Parameter Passing to functions 4) Empty parameter list in C means that the parameter list is not specified and function can be called with any parameters. In C, it is not a good idea to declare a function like fun(). To declare a function that can only be called without any parameter, we should use “void fun(void)”. **C++, an empty list means a function can only be called without any parameter. In C++, both void fun() and void fun(void) are same. 5)If in a C program, a function is called before its declaration then the C compiler automatically assumes the declaration of that function in the following way: int function name(); And in that case, if the return type of that function is different than 9 INT, compiler would show an error. Nested functions Functions can be nested? Answer is NO But the following code works without error 10 Nested functions This not nested function rather it is scope of code The view() function is accessible within fun() function Coding like this some times creates anomaly in the output 11 Example of Call by Value and Call by Reference 12 Pass Array as argument: void myFunction(int *param) { } void myFunction(int param[10]) { } void myFunction(int param[]) { } 13 Pass Array as argument: 14 Pass Multi Dimensional Array as argument: Need to specify the dimension of array otherwise compiler will consider the first [] as 1D array and generates error for the second [] 15 Recursive Function A function that calls itself is known as a recursive function. And, this technique is known as recursion. Stops at a specific condition. 16 Recursive Function Factorial Finding 17 Recursive Function Factorial Finding 18 Recursive Function Summation of Natural numbers 19 Recursive Function Fibonacci Series 20 Recursive Function **Recursive function makes the code more aristocratic What are the disadvantages of recursive programming over iterative programming? Note that both recursive and iterative programs have the same problem-solving powers, i.e., every recursive program can be written iteratively and vice versa is also true. The recursive program has greater space requirements than iterative program as all functions will remain in the stack until the base case is reached. It also has greater time requirements because of function calls and returns overhead. 21 Pointers What are pointers? A pointer is a variable: its value is a memory address like char variable has a character as a value and an int variable has an integer as a value whereas, the pointer variable has an address as a value pointers are variables that contain memory addresses as their values 22 Pointers The pointer in C language is a variable which stores the address of another variable. This variable can be of type int, char, array, function, or any other pointer. The size of the pointer depends on the architecture. However, in 32-bit architecture the size of a pointer is 2 byte. In my computer it is 4 bytes. (Not necessarily that 2byte for 32 bit so 8byte for 64 bit system) It depends on internal architecture. 23 Declaring a pointer The pointer in c language can be declared using * (asterisk symbol). It is also known as indirection pointer used to dereference a pointer. int *a;//pointer to int char *c;//pointer to char 24 Advantage of pointer Pointer reduces the code and improves the performance, it is used to retrieving strings, trees, etc. and used with arrays, structures, and functions. We can return multiple values from a function using the pointer. It makes you able to access any memory location in the computer's memory. Thousands of pointer might point to one address that reduces memory utilization. 25 Usage of pointer There are many applications of pointers in c language. 1) Dynamic memory allocation In c language, we can dynamically allocate memory using malloc() and calloc() functions where the pointer is used. 2) Arrays, Functions, and Structures Pointers in c language are widely used in arrays, functions, and structures. It reduces the code and improves the performance. 26 Example of pointer In this code *p and *p2 indicates pointer declaration. Only p indicates the value of the pointed address *p shows the address of the pointer itself Remember the syntax with * and without * 27 Common mistakes when working with pointers We want pointer pc to point to the address of c. Then, 28 Common mistakes when working with pointers But the following works. It is confusing. But true only at the time of declaration. Because int *p = &c; is equivalent to int *p: p = &c; 29 Pointers to array We can pass the address of array into pointer. Look at the following code and guess the output We can use the pointers to use like array index accessing 30 Some points about pointers The unary operators * and ++ : precedence: same associate: from right to left example: total += *start++; the pointer is incremented, not the value pointed to The use of the postfix form (start++ rather than ++start) means that the pointer is not incremented until after the pointed-to value is added to total 31 Some points about pointers *p represents the value stored in a pointer. ++ is increment operator used in prefix and postfix expressions. * is dereference operator. Precedence of prefix ++ and * is same and both are right to left associative. Precedence of postfix ++ is higher than both prefix ++ and * and is left to right associative. See the below example to understand the difference between ++*p, *p++ and *++p. 32 Some points about pointers arr[0] = 21, arr[1] = 30, *p = 21, q = 21 arr[0] = 21, arr[1] = 30, *p = 30, q = 21 arr[0] = 21, arr[1] = 30, *p = 40, q = 40 33 Some points about pointers *(ar + n): go to memory location ar, move over n units, and retrieve the value there Not get confused between *(dates+2) with *dates+2 *dates+2 means (*dates)+2: *(dates+2); /* value of the 3rd element of dates */ *dates+2; /* 2 added to the value of the 1st element */ 34 Array passing as pointers the four equivalent prototypes of a function sum() – with an array as one of parameters int sum(int *ar, int n); int sum(int *, int); int sum(int ar[], int n); int sum(int [], int); 35 Sorting: Bubble sort 36