Loading...

Advanced Topics (Recursion, Command Line args, Volatile etc.)

This chapter covers advanced concepts in C, including recursion, macros, and other useful programming techniques.

1. Recursion in C

Recursion is a process in which a function calls itself directly or indirectly to solve a problem.

Example: Factorial Using Recursion

#include <stdio.h>

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

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

2. Function Pointers

Function pointers allow passing functions as arguments to other functions.

Example: Function Pointer

#include <stdio.h>

void displayMessage() {
    printf("Hello from Function Pointer!\n");
}

int main() {
    void (*funcPtr)() = displayMessage;
    funcPtr(); // Calling function using pointer
    return 0;
}

3. Command-Line Arguments

C programs can take arguments from the command line using argc and argv.

Example: Command-Line Arguments

#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Program Name: %s\n", argv[0]);
    if (argc > 1)
        printf("Argument: %s\n", argv[1]);
    return 0;
}

4. Volatile Keyword

The volatile keyword tells the compiler that a variable's value may change at any time.

Example: Volatile Variable

volatile int flag = 0;

while (!flag) {
    // Wait until flag changes (useful in embedded systems)
}

5. Static and Register Storage Classes

Storage classes determine the scope and lifetime of variables in C.

  • Static: Retains value between function calls.
  • Register: Suggests storage in CPU registers for faster access.

Example: Static Variable

#include <stdio.h>

void counter() {
    static int count = 0;
    count++;
    printf("Count: %d\n", count);
}

int main() {
    counter();
    counter();
    counter();
    return 0;
}

This chapter introduced advanced C concepts, enhancing program efficiency and flexibility.

If you have any questions, feel free to ask. Thank you for reading!

Thankyou!