C Function Declaration and Definition

1. What is Function Declaration?

  • A function declaration (also called prototype) tells the compiler about a function’s name, return type, and parameters before its actual definition.

  • It does not contain the function body.

  • Helps the compiler check for correct function usage.

Syntax:

return_type function_name(parameter_list);

Example:

int add(int a, int b); // function declaration

2. What is Function Definition?

  • A function definition contains the actual body of the function — where the task is performed.

  • It tells the compiler what the function does.

Syntax:

return_type function_name(parameter_list) {
// function body
return value; // optional if return_type is void
}

Example:

int add(int a, int b) { // function definition
return a + b;
}

3. Calling a Function

  • You can call a function after declaration or definition.

  • Example:

#include <stdio.h>

int add(int a, int b); // function declaration

int main() {
int sum = add(5, 10); // function call
printf(“Sum = %d\n”, sum);
return 0;
}

int add(int a, int b) { // function definition
return a + b;
}

Output:

Sum = 15

Function declaration allows you to define the function later (after main).


4. Function Without Declaration

  • If the function is defined before main, a declaration is optional.

#include <stdio.h>

int add(int a, int b) { // definition before main
return a + b;
}

int main() {
printf(“Sum = %d\n”, add(5, 10));
return 0;
}


5. Function Declaration for Different Return Types

void greet(); // function with no return
float multiply(float a, float b); // function returning float
  • The compiler uses declaration to check type correctness when calling the function.


6. Key Points About Declaration and Definition

  1. Declaration (Prototype): informs the compiler about the function.

  2. Definition: provides the actual function body.

  3. A function must be declared before it is called, either via prototype or definition.

  4. Declarations allow calling a function before its definition, which is common in large programs.

  5. Function declaration improves code readability and compiler checking.

CodeCapsule

Sanjit Sinha — Web Developer | PHP • Laravel • CodeIgniter • MySQL • Bootstrap Founder, CodeCapsule — Student projects & practical coding guides. Email: info@codecapsule.in • Website: CodeCapsule.in

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *