Functions
wrap a block of code with a name so we don't need to write the same thing many times
Functions
A function is a collection of commands that perform tasks. printf()
and scanf()
are examples of functions. Functions provide abstraction, i.e. providing a simpler interface to hide complex implementations. We have already defined one before, it is main()
, the entry point to our program. Functions perform different tasks and may even return values.
Function Declaration
Being like variables, functions can only be accessed after the compiler knows about it, reading from the top. So to use a function in main()
For example, it either has to be defined above, or declared above and defined elsewhere.
If a function is declared before, then the compiler knows about its existence and expects it to be defined sometime in the future as it reads from file to file. The definition can be in any place in any file, as long as it is in some place the compiler expects.
If the function is declared, and used, but not defined, then the compiler will generate a reference to function not found
error.
The declaration/prototype is like so: <return_type> <function_name>(<parameters...>);
In <parameters...>
, each parameter can be simply <type_specifier>
without a parameter name, since they are not used immediately, though leaving a name may provide more details to how the function can be used.
If your function does not take any parameters (i.e. <parameters>
is empty), you can type in void
or leave it as it is.
Here is an example:
Example of void parentheses and empty parentheses:
Although the compiler throws a warning, the program works. However, if you change add extra arguments to
test_funcs
:The program cannot be compiled successfully. For more details about empty parentheses, read this.
Function Definition
Functions can be used by simply defining one. A declaration is not compulsory.
The most commonly used function definition syntax is as follows:
In <parameters...>
, parameters are separated by a ,
(comma operator). Each parameter consist of <type_specifier> <parameter_name>
. The type specifier specifies the type of parameter the function accepts, and the parameter name is some arbitrary name, used and only meaningful inside the function.
For example:
Then we can call it by square(3)
For example, it would return 9
at the calling place.
Function Call
A function call takes form of: <function_name>(<parameters...>)
A C function call/invocation is the same as those of mathematical functions, for which they accept parameters as inputs and return an output as a response, although C functions can also perform simple actions without any response. The parameters provided to a function call can be variables or literals, just anything that carries a value.
For example:
Last updated