Skip to main content

Declaring & Defining Functions In C

Function Declaration in C​

  • A function declaration, also known as a function prototype, is a statement that specifies the return type, name, and parameters of a function, but does not provide the implementation or working or actual body of the function.

  • Function declarations are used to inform the compiler about the signature of the function, so that it can check the correctness of function calls.

  • The syntax of a function declaration in C is:

return_type function_name(argument_list);

For example:

int sum(int a, int b);

Explanation

This function declaration states that the function sum returns an integer value and takes two integer arguments.

built-in functions

Function declarations of built-in functions are usually placed in header files, so that they can be easily shared and reused in multiple source files. The actual implementation of these function is provided in a separate source file.

Function Definition in C​

A function definition provides the implementation,working, actual body of the function of a function. In simple words function definition specifies the tasks it performs.

return_type function_name(argument_list) 
{
// function body
}

For example:

int sum(int a, int b)
{
int result;
result = a + b;
return result;
}

Explanation

  • This function definition specifies the implementation of the function sum, which takes two integer arguments and returns their sum as an integer value.

  • The function definition must match the function declaration in terms of the return type, name, and parameters.

  • The function body contains one or more statements that specify the tasks performed by the function.

  • The return statement is used to return the result of the function to the caller.

Differences between function declaration and definition​

Function DeclarationFunction Definition
Provides the compiler with the name, return type, and parameter list of a function.Provides the complete implementation of a function, including its code.
Also known as a function prototype.Also known as an implementation or definition of a function.
Uses the syntax return_type function_name(parameter list);.Uses the syntax return_type function_name(parameter list) { function body }.
Can appear in multiple places throughout the code, allowing for early binding of functions.Must appear exactly once in the code, usually in a separate file or at the bottom of the main file.
The function body is not included in the declaration.The function body is included in the definition.
tip
  • In C, it is generally a good practice to declare functions before they are called in the program, so that the compiler knows their signature and can check for any errors.

  • The definition of a function should be placed in a separate file or at the bottom of the main file, after all the functions that call it have been declared. This helps to make the code more readable and maintainable.