Understanding C Functions

Slide Note
Embed
Share

C functions are independent blocks of code that perform specific tasks when called, enhancing reusability and understandability in programming. This article covers topics such as C function declaration, return values, parameters, and function definitions in detail, offering insights into how functions are an essential aspect of C programming.


Uploaded on Sep 27, 2024 | 0 Views


Download Presentation

Please find below an Image/Link to download the presentation.

The content on the website is provided AS IS for your information and personal use only. It may not be sold, licensed, or shared on other websites without obtaining consent from the author. Download presentation by click this link. If you encounter any issues during the download, it is possible that the publisher has removed the file from their server.

E N D

Presentation Transcript


  1. C - FUNCTION

  2. What is C function a C function is an independent block of code that performs a specific task when called, it may return a value. Each function is essentially a small program, with its own variables and statements. All C programs are written using functions to improve re-usability, understandability and to keep track on them.

  3. C function declaration A function declaration, which is also called function prototype, specifies the name of the function, its return type, and a list of parameters if present. The general form of a function declaration is: return_type function_name (argument list or parameter list) { body of function; }

  4. Return Value A function may return one value at most. The return_type specifies the type of the returned value. A function may return any type, for example, char, int, float, or a pointer to some type. The only restriction is that it is not allowed to return an array or another function. However, it can return a pointer to an array or a function. If the return type is missing, the function is presumed to return a value of type int.

  5. Parameter or argument function A function may take a list of parameters, separated by commas. Each parameter is preceded by its type. For examples: void show(char ch); /* Declare a function with name show that takes a char parameter and returns nothing. */ double show(int a, float b); /* Declare a function with name show that takes an integer and a float parameter and returns a value of type double. */ int *show(int *p, double a); /* Declare a function with name show that takes as parameters a pointer to integer and a double parameter and returns a pointer to integer. */

  6. Function Definition The general form of a function definition is: return_type function_name(parameter_list) { /* Function body */ } The first line of the function s definition must agree with its declaration, with the difference that no semicolon is added at the end. The names of the parameters do not have to match the names given in the function s declaration. The code, or else the body of the function, contains declarations and statements enclosed in braces. The body of a function can be empty.

  7. Functions can be defined in several files; however, the definition of a function cannot be split between files. If a library function is used, the function has already been defined and compiled. The function s body is executed only if the function is called. The execution of a function terminates if either an exit statement (e.g., return) is called or its last statement is executed. For example // example program for function definition

  8. #include <stdio.h> void test(void); /* Function declaration. */ int main(void) { test(); /* Function call. */ return 0; } void test(void) /* Function definition. */ { /* Function body. */ printf( my \n"); }

  9. /*Example program to show how to declare a function in a different file. Create a file, e.g., sample.h, copy the declaration inside, remove the declaration from the source file, and use the #include directive to include sample.h */ #include <stdio.h> #include sample.h" int main(void)

  10. A function is not allowed to be defined inside another function. However, the declaration of a function can be put inside the body of the calling function. For example: int main(void) { void test(void); test(); return 0; }

  11. If the definition precedes its call, it is safe to omit the declaration of the function. For example: #include <stdio.h> void test(void) { printf( My \n"); } int main(void) { test(); return 0; }

  12. The Return Statement The return statement is used to terminate immediately the execution of a function. The return statement can be use to terminate the main() function, that is, the program itself. Consider the following example //the program terminates if the user enters the value 2, otherwise it outputs the input value. #include <stdio.h> int main(void) { int num; while(1) { printf("Enter number: "); scanf("%d", &num); if(num == 2) return 0; /* Terminate the program. */ else printf("Num = %d\n", num); } return 0; }

  13. Notice that the last return will never be executed, since the first return terminates the program. The value returned by main() indicates the termination status of the program. The value 0 indicates normal termination, whereas a nonzero value typically indicates abnormal termination. If the function returns nothing, we just write return. The return statement at the end of a void function is unnecessary because the function will return automatically.

  14. /*the avg() function compares the values of the two parameters, and if they are different, it displays their average. If they are the same, the function terminates */ void avg(int a, int b) { /* Function body. */ if(a == b) return; printf("%f\n", (a+b)/2.0); /* The return statement is unnecessary. */ }

  15. If the function is declared to return a value, each return statement should be followed by a value. For example, //avg() function to return an integer value: int avg(int a, int b) { if(a == b) return 0; printf("%f\n", (a+b)/2.0); return 1;

  16. Notice that the second return statement at the end of the function can be omitted. The function would return an undefined value, which is definitely undesirable. Therefore, it is strongly recommend that a non-void function always return a value, even if we are allowed not to do it. The type of the returned value should match the function s return type. If it does not match, the compiler will convert the returned value, if possible, to the return type. For example:

  17. int test() { return 4.9; } Since test() is declared to return an int value, the returned value is implicitly converted to int. Therefore, the function returns 4.

  18. Function Call A function can be called as many times as needed. When a function is called, the execution of the program continues with the execution of the function s code. The compiler allocates memory to store the function s parameters and the variables that are declared within its body.

  19. How to call C functions in a program? There are two ways that a C function can be called from a program. They are, Call by value Call by reference 1. Call by value: In call by value method, the value of the variable is passed to the function as parameter. The value of the actual parameter can not be modified by formal parameter. Different Memory is allocated for both actual and formal parameters. Because, value of actual parameter is copied to formal parameter. Note: Actual parameter This is the argument which is used in function call. Formal parameter This is the argument which is used in function definition

  20. /* Example program for C function (using call by value): In this program, the values of the variables m and n are passed to the function swap . These values are copied to formal parameters a and b in swap function and used. */ #include<stdio.h> /* function prototype, also called function declaration*/ void swap(int a, int b); int main() { int m = 22, n = 44; // calling swap function by value printf(" values before swap m = %d \n and n = %d", m, n); swap(m, n); } void swap(int a, int b) { int tmp; tmp = a; a = b; b = tmp; printf(" \nvalues after swap m = %d\n and n = %d", a, b); }

  21. 2. Call by reference: In call by reference method, the address of the variable is passed to the function as parameter. The value of the actual parameter can be modified by formal parameter. Same memory is used for both actual and formal parameters since only address is used by both parameters. Example program for C function (using call by reference): In this program, the address of the variables m and n are passed to the function swap . These values are not copied to formal parameters a and b in swap function. Because, they are just holding the address of those variables. This address is used to access and change the values of the variables.

  22. #include<stdio.h> /*function prototype, also called function declaration*/ void swap(int *a, int *b); int main() { int m = 22, n = 44; /*calling swap function by reference */ printf("values before swap m = %d \n and n = %d",m,n); swap(&m, &n); } void swap(int *a, int *b) { int tmp; tmp = *a; *a = *b; *b = tmp; printf("\n values after swap a = %d \nand b = %d", *a, *b); }

  23. All C functions can be called either with arguments or without arguments in a C program. These functions may or may not return values to the calling function. Now, we will see simple example C programs for each one of the below. C function with arguments (parameters) and with return value C function with arguments (parameters) and without return value C function without arguments (parameters) and without return value C function without arguments (parameters) and with return value

  24. S.no C function syntax int function ( int ); // function declaration function ( a ); // function call int function( int a ) // function definition {statements; return a;} with arguments and with return values 1 void function ( int ); // function declaration function( a ); // function call void function( int a ) // function definition {statements;} with arguments and without return values 2 void function(); // function declaration function(); // function call void function() // function definition {statements;} without arguments and without return values 3 int function ( ); // function declaration function ( ); // function call int function( ) // function definition {statements; return a;} without arguments and with return values 4

  25. If the return data type of a function is void, then, it can t return any values to the calling function. If the return data type of the function is other than void such as int, float, double etc , then, it can return values to the calling function. 1. /*Example program for with arguments & with return value: In this program, integer, array and string are passed as arguments to the function. The return type of this function is int and value of the variable a is returned from the function. The values for array and string are modified inside the function itself.*/ #include<stdio.h> #include<string.h> int function(int, int[], char[]);

  26. int main() { int i, a = 20; int arr[5] = {10,20,30,40,50}; char str[30] = "\ WhoareYou\""; printf(" ***values before modification***\n"); printf("value of a is %d\n",a); for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d\n",i,arr[i]); } printf("value of str is %s\n",str); printf("\n ***values after modification***\n"); a= function(a, &arr[0], &str[0]); printf("value of a is %d\n",a);

  27. for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d\n", i, arr[i]); } printf("value of str is %s\n", str); return 0; } int function(int a, int *arr, char *str) { int i; a = a+20; arr[0] = arr[0]+50; arr[1] = arr[1]+50; arr[2] = arr[2]+50; arr[3] = arr[3]+50; arr[4] = arr[4]+50; strcpy(str,"\"modified string\""); return a; }

  28. 2. /*Example program for with arguments & without return value: In this program, integer, array and string are passed as arguments to the function. The return type of this function is void and no values can be returned from the function. All the values of integer, array and string are manipulated and displayed inside the function itself. */ #include<stdio.h> void function(int, int[], char[]); int main() { int a = 20;

  29. int arr[5] = {10,20,30,40,50}; char str[30] = "\ WhoareYou\""; function(a, &arr[0], &str[0]); return 0; } void function(int a, int *arr, char *str) { int i; printf("value of a is %d\n\n",a); for (i=0;i<5;i++) { // Accessing each variable printf("value of arr[%d] is %d\n",i,arr[i]); } printf("\nvalue of str is %s\n",str); }

  30. 3. /* Example program for without arguments & without return value: In this program, no values are passed to the function test and no values are returned from this function to main function.*/ #include<stdio.h> void test(); int main() { test(); return 0; } void test() { int a = 50, b = 80; printf("\nvalues : a = %d and b = %d", a, b); }

  31. 4. /*Example program for without arguments & with return value: In this program, no arguments are passed to the function sum . But, values are returned from this function to main function. Values of the variable a and b are summed up in the function sum and the sum of these value is returned to the main function.*/ #include<stdio.h> int sum(); int main() { int addition; addition = sum(); printf("\nSum of two given values = %d", addition); return 0; } int sum() { int a = 50, b = 80, sum; sum = a + b; return sum; }

  32. Do you know how many values can be return from C functions? Always, Only one value can be returned from a function. If you try to return more than one values from a function, only one value will be returned that appears at the right most place of the return statement. For example, if you use return a,b,c in your function, value for c only will be returned and values a, b won t be returned to the program. In case, if you want to return more than one values, pointers can be used to directly change the values in address instead of returning those values to the function.

  33. A call to a function that does not take any parameters is made by writing the function name followed by a pair of empty parentheses. The calling function does not pass any data to the called function. E.G. // In the following program, the calling function, //that is, main(), calls twice the test() function: #include <stdio.h> void test(void); int main(void) Function Call without Parameters

  34. { printf("Call_1 "); test(); /* Function call. The parentheses are empty, because the function does not take any parameters. */ printf("Call_2 "); test(); /* Second call. */ return 0; } void test(void) { /* Function body. */ int i; for(i = 0; i < 2; i++) printf("In "); }

  35. At the first call of test(), the program continues with the execution of the function body. When test() terminates, the execution of the program returns to the calling point and continues with the execution of the next statement. Therefore, the main program displays Call_2 and calls test() again. As a result, the program displays Call_1 In In Call_2 In In. A common oversight is to omit the parentheses when the function is called.

  36. //In the following program, test() returns an integer value. #include <stdio.h> int test(void); int main(void) { int sum; sum = test(); /* Function call. The returned value is stored in sum. */ printf("%d\n", sum); return 0; } int test(void) { int i = 10, j = 20; return i+j; }

  37. test() declares two integer variables with values 10 and 20 and returns their sum. This value is stored into sum and the program displays 30. Function Call with Parameters A call to a function that takes parameters is made by writing the function name followed by a list of arguments, enclosed in parentheses. Using arguments is one way to pass information to a function. The difference between parameter and argument is that the term parameter refers to the variables that appear in the definition of the function, while the term argument refers to the expressions that appear in the function call.

  38. //consider the following program: #include <stdio.h> int test(int x, int y); int main(void) { int sum, a = 10, b = 20; sum = test(a, b); /* The variables a and b become the function's arguments. */ printf("%d\n", sum); return 0; } int test(int x, int y) /* The variables x and y are the function's parameters. */ { return x+y; }

  39. /*Write two functions that take an integer parameter and return the square and the cube of this number, respectively. Write a program that reads an integer and uses the functions to display the sum of the number s square and cube*/ #include <stdio.h> int square(int a); int cube(int a); int main(void) { int i, j, k; printf("Enter number: "); scanf("%d", &i); j = square(i); k = cube(i);

  40. printf("sum = %d\n", j+k); /* Without declaring the j and k variables, we could write printf("sum = %d\n", square(i)+cube(i)); */ return 0; } int square(int a) { return a*a; } int cube(int a) { return a*a*a; }

  41. /*Write a function that takes as parameters three values and returns the minimum of them. Write a program that reads the grades of three students and uses the function to display the minimum.*/ #include <stdio.h> float min(float a, float b, float c); int main(void) { float i, j, k; printf("Enter grades: "); scanf("%f%f%f", &i, &j, &k); printf("Min grade = %f\n", min(i, j, k)); return 0; }

  42. float min(float a, float b, float c) { if(a <= b && a <= c) return a; else if(b < a && b < c) return b; else return c; }

  43. /*Write a function that takes as parameters an integer and a character and displays the character as many times as the value of the integer. Write a program that reads an integer and a character and uses the function to display the character.*/ #include <stdio.h> void show_char(int num, char ch); int main(void) { char ch; int i; printf("Enter character: "); scanf("c", &ch);

  44. scanf("%d", &i); show_char(i, ch); return 0; } void show_char(int num, char ch) { int i; for(i = 0; i < num; i++) printf("%c", ch); } NOTE: The return type of show_char() is declared void, because it does not return any value.

  45. /*Write a function that takes as parameters three floats and returns the average of those within [1,2]. Write a program that reads three floats, calls the function, and displays the return value*/ #include <stdio.h> double avg(double a, double b, double c); int main(void) { double i, j, k, ret; printf("Enter prices: "); scanf("%lf%lf%lf", &i, &j, &k);

  46. ret = avg(i, j, k); if(ret == -1) printf("No value in [1, 2]\n"); else printf("Avg = %f\n", ret); return 0; } double avg(double a, double b, double c) { int k = 0; double sum = 0; if(a >= 1 && a <= 2) { sum += a;

  47. k++; } if(b >= 1 && b <= 2) { sum += b; k++; } if(c >= 1 && c <= 2) { sum += c; k++; } if(k != 0) return sum/k; else return -1;

  48. Library Functions Library functions in C language are inbuilt functions which are grouped together and placed in a common place called library. Each library function in C performs specific operation. We can make use of these library functions to get the pre-defined output instead of writing our own code to get those outputs. These library functions are created by the persons who designed and created C compilers. All C standard library functions are declared in many header files which are saved as file_name.h. Actually, function declaration, definition for macros are given in all header files. We are including these header files in our C program using #include<file_name.h> command to make use of the functions those are declared in the header files. When we include header files in our C program using #include<filename.h> command, all C code of the header files are included in C program. Then, this C program is compiled by compiler and executed.

  49. S.No Header file Description This is standard input/output header file in which Input/Output functions are declared 1 stdio.h 2 conio.h This is console input/output header file 3 string.h All string related functions are defined in this header file 4 stdlib.h This header file contains general functions used in C programs 5 math.h All maths related functions are defined in this header file 6 time.h This header file contains time and clock related functions 7 ctype.h All character handling functions are defined in this header file

  50. 8 stdarg.hVariable argument functions are declared in this header file Signal handling functions are declared in this file 9 signal.h 10 setjmp.hThis file contains all jump functions 11 locale.hThis file contains locale functions Error handling functions are given in this file 12 errno.h 13 assert.hThis contains diagnostics functions

Related