A C program generally is a collection of functions. Functions are based on the concept that if we have a large problem, it is wise to divide that problem into smaller units and then solve each unit separately which is supposed to be much easier.
Before a function can be used in a C program, it has to be declared and defined just as a variable (declaring a function is not compulsory but I recommend it as a good programming practice. Because you will have the declarations of all your functions in one place and it will be easier to maintain them).
A function is declared as
function_name (type , type , ...);
And it is defined as
function_name (type , type , ...) { return; /* function body */ }
Note that C is not a nested language. So there can be no nesting of one function inside another. The return_value and arguments are optional. Also the return statement in the function body is optional. It is important that the declaration and the definition have the same signature else the compiler will complain.
The example of a C program with function is as below where we convert temperature from celcius to fahrenheit:
int CelciusToFahrenheit(int celcius); /* Declaration of the function */
int CelciusToFahrenheit(int celcius) /* Definition of the function */
{
int fahrenheit = 0;
fahrenheit = (9.0/5) * celcius + 32; /* formula to convert celcius to fahrenheit.
Note the 9.0 is used for int to float implicit type
conversion for better precision */
return fahrenheit;
}
main()
{
int celcius = 35;
printf("Temperature in Celcius = %dn", celcius);
printf("Temperature in Fahrenheit = %dn", CelciusToFahrenheit(celcius)); /* Calling the function */
}
The CelciusToFahrenheit() function is shown simplified. A better way to write this function is
int CelciusToFahrenheit(int celcius) /* Definition of the function */
{
return (9.0/5) * celcius + 32; /* this shows that the return value can be any valid expression */
}
The return value and the function arguments can be any type i.e int, float, char, etc. The function arguments are call by value and not call by reference. In call by reference, if we modify the function arguments inside the function, the changes are reflected in the actual arguments in the calling code. But in call by value, the function arguments are local to the function and any changes are not reflected back to the actual arguments. This is a good thing because the code is less error prone when the variables are localized. In the above celcius to fahrenheit example, the celcius variable in the main program is different from the celcius argument of the function which is local to the function.


