C function calls
Created By: chatGPT
In C programming, a function is a block of code that performs a specific task. To use a function, you typically call it by its name and provide any required arguments. Here’s a simple example showing how to define a function and call it.
c
#include <stdio.h>
// Function definition
void greet() {
printf("Hello, World!\n");
}
int main() {
// Function call
greet();
return 0;
}
Functions can also accept parameters, which allow you to pass data to them. Here is an example of a function that takes two integers as arguments and returns their sum.
c
#include <stdio.h>
// Function that returns the sum of two numbers
int add(int a, int b) {
return a + b;
}
int main() {
int x = 5, y = 10;
// Calling the add function
int sum = add(x, y);
printf("Sum: %d\n", sum);
return 0;
}
You can also have functions that return values. The return type of a function must be specified in its definition. Here’s an example of a function that calculates the factorial of a number.
c
#include <stdio.h>
// Function to calculate factorial
int factorial(int n) {
if (n <= 1) {
return 1;
}
return n * factorial(n - 1);
}
int main() {
int num = 5;
// Calling the factorial function
printf("Factorial of %d is %d\n", num, factorial(num));
return 0;
}
Functions can be declared before they are defined. This practice improves code readability and allows for function calls to occur in any order. Here's how to declare a function prior to its definition.
c
#include <stdio.h>
// Function declaration
void displayMessage();
int main() {
// Function call
displayMessage();
return 0;
}
// Function definition
void displayMessage() {
printf("This is a message from a function!\n");
}
In C, you can also pass parameters by reference using pointers. This is useful when you need a function to modify the original variable. Here’s an example demonstrating this concept via a function that swaps two numbers.
c
#include <stdio.h>
// Function to swap two numbers using pointers
void swap(int *x, int *y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a = 5, b = 10;
// Calling the swap function
swap(&a, &b);
printf("After swapping: a = %d, b = %d\n", a, b);
return 0;
}