



Study with the several resources on Docsity
Earn points by helping other students or get them with a premium plan
This page cannot be seen from the preview
Don't miss anything!




A function in C is a set of statements that when called perform some specific task. It is the basic building block of a C program that provides modularity and code reusability. Syntax of Functions in C The syntax of function can be divided into 3 aspects:
Function Call A function call is a statement that instructs the compiler to execute the function. We use the function name and parameters in the function call. Example #include // Function that takes two parameters // a and b as inputs and returns // their sum int sum(int a, int b) { return a + b; } int main() { // Calling sum function and // storing its value in add variable int add = sum(10, 30); printf("Sum is: %d", add); return 0; } Function Return Type Function return type tells what type of value is returned after all function is executed. When we don’t want to return a value, we can use the void data type. Example: int func(parameter_1,parameter_2); Function Arguments Function Arguments (also known as Function Parameters) are the data that is passed to a function. Example: int function_name(int var1, int var2);
2. User Defined Function Functions that the user creates are known as User-Defined functions. User- defined functions can be improved and modified according to the need of the programmer. Advantages of User-Defined Functions
#include void swap(int var1, int var2) { int temp = var1; var1 = var2; var2 = temp; } int main() { int var1 = 3, var2 = 2; printf("Before swap Value of var1 and var2 is: %d, %d\n", var1, var2); swap(var1, var2); printf("After swap Value of var1 and var2 is: %d, %d", var1, var2); return 0; }
2. Pass by Reference The caller’s actual parameters and the function’s actual parameters refer to the same locations, so any changes made inside the function are reflected in the caller’s actual parameters. #include void swap(int *var1, int *var2) { int temp = *var1; *var1 = *var2; *var2 = temp; } int main() { int var1 = 3, var2 = 2; printf("Before swap Value of var1 and var2 is: %d, %d\n", var1, var2); swap(&var1, &var2); printf("After swap Value of var1 and var2 is: %d, %d", var1, var2); return 0; }