Quick Learnology

Pointers

Introduction to Pointers:

A pointer is a variable that stores the memory address of another variable. Pointers allow for dynamic memory allocation, manipulation of data stored in memory, and passing variables to functions by reference.

Call by Value and Call by Reference:

In C, arguments can be passed to functions using either call by value or call by reference.

Call by Value

In call by value, a copy of the argument is passed to the function. Any changes made to the argument inside the function will not affect the original value.

Call by reference:

In call by reference, the address of the argument is passed to the function. Any changes made to the argument inside the function will affect the original value.

For example

#include <stdio.h>

void swap(int *a, int *b) {
   int temp = *a;
   *a = *b;
   *b = temp;
}

int main() {
   int x = 10, y = 20;
   printf("Before swapping: x = %d, y = %d", x, y);
   swap(&x, &y);
   printf("After swapping: x = %d, y = %d", x, y);
   return 0;
}

Here, the swap function uses pointers to swap the values of x and y.

Back to Function Calls:

Pointers can also be used to pass function addresses as arguments to other functions, allowing for function callbacks.

Recursion

Recursion is a technique in C where a function calls itself to solve a problem. Recursion can be used to solve problems that can be broken down into smaller sub-problems. However, it is important to ensure that the recursive function has a terminating condition, otherwise it will go into an infinite loop.

For example :

#include <stdio.h>

int factorial(int n) {
   if (n == 0)
      return 1;
   else
      return n * factorial(n - 1);
}

int main() {
   int n = 5;
   printf("The factorial of %d is %d", n, factorial(n));
   return 0;
}

Here, the function factorial calculates the factorial of a number using recursion.

Leave a Comment

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