Monday, January 6, 2025
HomeProgrammingC Functions

C Functions

In C, a function is a block of code designed to perform a specific task. Functions help organize code, promote reusability, and improve readability.

Structure of a Function in C
c
return_type function_name(parameter_list) {
// Function body
return value; // Optional for void functions
}

Key Components
1. Return Type: Specifies the type of value the function will return (e.g., int, float, void for no return).
2. Function Name: Identifier to call the function.
3. Parameter List: Variables passed to the function as input (optional).
4. Function Body: Contains the code to be executed.
5. Return Statement: Sends a value back to the caller (optional for void functions).

See also  How to Print in Java

Types of Functions
1. Library Functions: Predefined functions provided by C libraries (e.g., printf, scanf, strlen).
2. User-Defined Functions: Custom functions created by the programmer.

Example of a Function
#### Function Definition
c
#include <stdio.h>

// Function to add two numbers
int add(int a, int b) {
return a + b;
}

int main() {
int result = add(5, 3); // Call the function
printf(“Sum: %d\n”, result);
return 0;
}

Function Declaration (Prototype)
Before using a function, its prototype should be declared (except if defined before use). It tells the compiler about the function’s name, return type, and parameters.

See also  Accessor and Mutator in Java

c
int add(int a, int b); // Function prototype

Function Call
A function is called by using its name and passing the required arguments.

c
int result = add(10, 20);

Void Functions
Void functions do not return any value.

c
void greet() {
printf(“Hello, World!\n”);
}

int main() {
greet(); // Output: Hello, World!
return 0;
}

Key Concepts
1. Pass by Value: The function receives a copy of the arguments, so changes inside the function do not affect the original values.
2. Recursion: A function can call itself for tasks like factorial or Fibonacci.

See also  What is the function of a monitor?

Example of recursion:
c
int factorial(int n) {
if (n == 0) return 1;
return n * factorial(n – 1);
}

Functions in C are fundamental for creating modular, reusable, and maintainable programs

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x