Function in C Types Definitions Example
What is a Function in C?
A function in C is a block of code that performs a specific task. Functions are essential for organizing and structuring code, promoting modularity, reusability, and maintainability. They help in breaking down complex programs into smaller, manageable units.
Structure of a Function
A function in C consists of two main parts:
Function Declaration: This informs the compiler about the function's existence, including its name, return type, and parameter list (if any). The syntax for a function declaration is:
C
returnType functionName(parameterList);
For example, the function declaration int add(int a, int b); declares a function named add that takes two integer parameters, a and b, and returns an integer value.
Function Definition: This provides the actual code that the function executes when it's called. The syntax for a function definition is:
C
returnType functionName(parameterList) {
// Function body
}
For example, the function definition int add(int a, int b) { int sum = a + b; return sum; } defines the function add to calculate the sum of two integer values.
Types of Functions in C
User-Defined Functions: These are functions created by the programmer to address specific needs within the program.
Library Functions: These are predefined functions provided by the C standard library and offer a wide range of functionalities.
Example of a User-Defined Function:
C
#include <stdio.h>
int add(int a, int b) {
int sum = a + b;
return sum;
}
int main() {
int num1, num2;
printf("Enter two numbers: ");
scanf("%d %d", &num1, &num2);
int result = add(num1, num2);
printf("The sum of %d and %d is %d.", num1, num2, result);
return 0;
}
This program defines a user-defined function add that takes two integer inputs and returns their sum. The main function calls the add function to calculate the sum of two user-provided numbers and prints the result.
Example of a Library Function:
C
#include <stdio.h>
int main() {
printf("Hello, World!\n");
return 0;
}
This program uses the standard library function printf to print the message "Hello, World!" to the console.
Short Definitions:
Function Name: The identifier that uniquely identifies the function.
Return Type: The data type of the value returned by the function (void indicates no return value).
Parameters: Optional input values passed to the function.
Function Body: The code that is executed when the function is called.
keyword:
No comments: