A Function play an import role in a program development. A function contain of number of statements that perform a task. Instead of writing a block of code again and again, we can create a function, write the code inside it and call the function as many times as required. When the function is call, the controller is passed to that function, execute the function statements and return from where it is called.
1. Prototype or declaration: A function declaration tells the compiler by giving details such as function name, the number, and type of arguments and the data type of return values in advance used in the program.
return_datatype function_name(datatype1, datatype2, …);
2. Calling: Calling a function means a controller is passed to a function and return back after executing the function, while calling a function mention the function name with its parameter.
variable_name = function_name(variable_name1, variable_name2, …);
3. Body or definition: The function body contains a collection of statements that define the logic to solve a particular problem.
return_datatype function_name(datatype variable1, datatype variable2, …) { statement 1; statement 2; }
Return data type: A function may or may not return a value, but it cannot return more than one value at a time. The return data type returns the result back from where a function is called. If the function is not returning any value, in that case you must prefix void keyword before function name. If no data type is specified, the default return data type is integer.
Function name: It is a identifier name, defined by the user, to name a function.
Parameter: A parameter is like a placeholder. When a function is called, you can pass a value to that function via parameter. Data type in parameter is also referred to as the actual parameter or argument. The parameter list refers to the data type, argument order, and number of the arguments in a function. Parameters are optional, or you can provide any number of arguments there is no maximum limit.
Example 1: Print a message "Hello" using a function with no argument and no return type.
void fun(); // function prototype or function declaration void main() { printf("I am in main() function\n"); fun(); fun(); printf("I am back in main() function\n"); getch(); } void fun() { printf ("Hello! I am in user-defined function\n"); }
Example 2: WAF to find sum of 2 numbers using function with argument and no return type.
void sun(int, int); void main() { int a, b; printf("Enter 2 numbers: "); scanf("%d",&a); scanf("%d",&b); sun(a, b); getch(); } void sun(int a, int b) { int c; c=a+b; printf("Sum = %d",c); }
Example 3: WAF to find sum of 2 numbers using function with argument and with return type.
int sun(int, int); void main() { int a, b, c; printf("Enter 2 numbers: "); scanf("%d",&a); scanf("%d",&b); c=sun(a, b); printf("Sum = %d",c); getch(); } int sun(int a, int b) { int c; c=a+b; return c; }