A function is a collection of statements that work together to complete a job. Every C programme contains at least one function, main(), and even the simplest programmes can specify more functions.
You may break your code into different functions. It's up to you how you split your code into various functions, but logically, each function should fulfil a specific purpose.
The name, return type, and parameters of a function are all specified in a function declaration. The actual body of the function is provided by a function definition.
The C standard library includes a number of built-in functions that you may use in your application. Strcat(), for example, concatenates two strings, memcpy() copies one memory address to another, and many other methods.
A function is sometimes known as a method, a subroutine, a process, and so on.
In the C programming language, a function definition takes the following general form:
The source code for a function named max is shown below (). The greatest value between two arguments, num1 and num2, is returned by this function.
A function declaration gives the compiler the name of the function and how to invoke it. The function's actual body can be specified independently.
Return type function name( parameter list ); return type function name( parameter list ); return type function name( parameter list ); return type function name( parameter list ); return type
The function definition for the above-mentioned function max() is int max(int num1, int num2);
The names of the parameters are unimportant in function declarations; just their types are necessary, thus the following declaration is equally legal.
When a function is defined in one source file and called in another, a function declaration is necessary. In this instance, the function should be declared at the start of the file invoking the function.
When you create a C function, you must define what the function must perform. To utilise a function, you must first call it to accomplish the specified job.
When a programme calls a function, control is passed from the calling programme to the called function. A called function performs a specific job and then returns programme control to the main programme when its return statement or function-ending closing brace is reached.
You just need to supply the appropriate arguments along with the function name to call a function, and if the function returns a result, you may save it. For instance,
We compiled the source code while keeping max() and main(). When you execute the finished executable, you'll get the following result:
If a function is going to utilise arguments, it has to define variables that will take the arguments' values. These variables are known as the function's formal parameters.
Formal arguments are generated when the function is entered and deleted when it is exited, just like other local variables inside the function.
There are two methods to give parameters to a function when calling it:
|