Defining a Functions
- In a Functions definition, first line consists of data type of the value to be returned followed by name of the function and then the arguments in pair of parentheses.
- These arguments are called formal or dummy arguments.
- The type of the formal arguments is declared immediately after it.
- If there are no formal arguments, then the keyword void can be written in the parentheses. If the function is not returning any value, its return type is also specified as void. void is the keyword which implies nothing.
- The body of the function is enclosed in braces. If the function is returning a value, there must be at least one return statement in the function to send back the value. However if return type is void, the return statement is not compulsory.
Declaration of Functions
- Similar to variables, all functions must be declared before they are used in the program.
- C allows the declaration of functions in the calling program with the help of functions prototype.
- The general form of a function prototype in the calling program is given below:
<type> <name> (arguments);
- <type> is the type of value which is returned by the functions.
- <name> is user defined name of functions.
- argument is a list of parameters.
- ; -> The Semicolon marks the end of prototype declaration.
Free Hand-Written Notes
e.g. the Prototype declarations for some functions are given below.
float area (float r);
void message();
int sum (int x, int y);
- message functions do not receive any arguments and not returning any value, area functions receives arguments r and returns float value and sum function receives two arguments x and y and returning integer value.
- In C, if functions is returning integer value then it is optional to be declared.
Syntax:
Let’s take an syntax of Defining a Functions in C Language,
return_type function_name(parameters) {
// function body
}
In the Syntax, the “return_type” specifies the type of the value which function can return. “function_name” is the name of the function and ‘parameters” are the input value which accepts by the functions.
Now, Let’s take an Example of Defining a Function,
Example:
Let’s take an example of Defining a Function in C Language,
#include <stdio.h> // Function declaration int add(int a, int b) { return a + b; } int main() { int num1 = 5, num2 = 3; int sum = add(num1, num2); printf("Sum: %d\n", sum); return 0; }
Explanation about Example:
In this example, we define a “add” function which is used for return the sum of the integers. And then we call this function inside the main function to get print values or output.