C Programming Interview Questions

author image Hirely
at 07 Jan, 2025

Question: What is a function pointer in C?

Answer:

A function pointer in C is a pointer that points to a function instead of pointing to a variable. It allows you to store the address of a function and call it indirectly through the pointer. This is useful when you want to pass functions as arguments to other functions, implement callbacks, or handle dynamic function selection at runtime.

Syntax of a Function Pointer:

To declare a function pointer, you need to know the signature (return type and parameter types) of the function it will point to.

General Syntax:

return_type (*pointer_name)(parameter_types);
  • return_type: The return type of the function the pointer will point to.
  • pointer_name: The name of the pointer.
  • parameter_types: The types of parameters the function accepts.

Example:

For a function that returns an int and takes two int parameters:

int (*func_ptr)(int, int);

This declares func_ptr as a pointer to a function that returns an int and takes two int parameters.

Example Code:

Let’s break down the example of a function pointer:

#include <stdio.h>

// A simple function that adds two integers
int add(int a, int b) {
    return a + b;
}

// A function that subtracts two integers
int subtract(int a, int b) {
    return a - b;
}

int main() {
    // Declare a function pointer that points to functions with the signature (int, int) -> int
    int (*func_ptr)(int, int);

    // Point to the 'add' function
    func_ptr = &add;

    // Use the function pointer to call 'add'
    printf("Addition: %d\n", func_ptr(5, 3));  // Output: 8

    // Point to the 'subtract' function
    func_ptr = &subtract;

    // Use the function pointer to call 'subtract'
    printf("Subtraction: %d\n", func_ptr(5, 3));  // Output: 2

    return 0;
}

Output:

Addition: 8
Subtraction: 2

Breakdown of the Example:

  1. Function Definitions:

    • add(int a, int b): This function returns the sum of two integers.
    • subtract(int a, int b): This function returns the difference of two integers.
  2. Function Pointer Declaration:

    int (*func_ptr)(int, int);

    This declares func_ptr as a pointer to a function that takes two int parameters and returns an int.

  3. Assigning Function to the Pointer:

    func_ptr = &add;

    We assign the address of the add function to func_ptr.

  4. Calling the Function Using the Pointer:

    printf("Addition: %d\n", func_ptr(5, 3));  // Calls add function via func_ptr

    We use func_ptr to call the function it points to, which is add. This is equivalent to calling add(5, 3).

  5. Switching Functions:

    func_ptr = &subtract;

    We change the function pointer to point to the subtract function and then call it similarly.

Use Cases for Function Pointers:

  1. Callbacks: Function pointers are often used for implementing callbacks, where a function can take another function as an argument and call it within its body. This is common in event-driven programming or when implementing generic functions.

    #include <stdio.h>
    
    // Callback function type
    void callback_function(int a, int b) {
        printf("Callback called with %d and %d\n", a, b);
    }
    
    // Function that accepts a callback
    void do_something(void (*callback)(int, int)) {
        callback(5, 10);  // Call the passed-in function
    }
    
    int main() {
        // Pass the callback function to do_something
        do_something(callback_function);
        return 0;
    }

    Output:

    Callback called with 5 and 10
  2. Implementing a Menu System: A common use of function pointers is to implement a menu-driven program where the user can choose different operations, and each operation corresponds to a different function.

    #include <stdio.h>
    
    // Functions for different operations
    void add_operation() {
        printf("Performing addition\n");
    }
    
    void subtract_operation() {
        printf("Performing subtraction\n");
    }
    
    void multiply_operation() {
        printf("Performing multiplication\n");
    }
    
    int main() {
        // Array of function pointers
        void (*operations[3])() = {add_operation, subtract_operation, multiply_operation};
        
        // Example of menu choice
        int choice = 1;  // User selects 'subtract'
        
        // Call the corresponding function via function pointer
        operations[choice]();  // Calls subtract_operation()
    
        return 0;
    }

    Output:

    Performing subtraction
  3. Dynamic Function Selection: You can use function pointers to select and execute functions dynamically based on user input or configuration files, making your program more flexible.

Function Pointer as Arguments:

Function pointers can also be passed as arguments to other functions. This is particularly useful in scenarios like sorting algorithms, where the comparison function can be passed dynamically.

#include <stdio.h>

// Function that takes a function pointer as an argument
void execute_function(int (*func_ptr)(int, int)) {
    printf("Result: %d\n", func_ptr(10, 5));
}

// A simple function for demonstration
int multiply(int a, int b) {
    return a * b;
}

int main() {
    // Pass function pointer to execute_function
    execute_function(multiply);
    return 0;
}

Output:

Result: 50

Conclusion:

  • A function pointer is a powerful tool in C that allows you to point to and call functions dynamically.
  • It enables callbacks, dynamic function selection, and event-driven programming.
  • Function pointers provide flexibility and efficiency in many advanced programming scenarios, especially in cases where you need to pass functions as arguments or execute different functions based on user input.

Question: What is the purpose of the static keyword in C?

Answer:

In C, the static keyword serves multiple purposes, depending on its context—whether it is used inside a function or outside a function. The primary purposes of static are to manage the scope and lifetime of variables and to control the visibility of functions or variables.

1. Static Variables inside Functions (Local Static Variables)

When static is used inside a function, it changes the behavior of the variable from a local variable to a static local variable. A static local variable retains its value between function calls, but its scope is still limited to the function.

  • Scope: A static variable inside a function can only be accessed within that function.
  • Lifetime: Unlike regular local variables, which are destroyed when the function exits, static variables persist for the entire lifetime of the program.

Syntax:

static data_type variable_name;

Example:

#include <stdio.h>

void counter() {
    static int count = 0;  // Static variable to persist between function calls
    count++;
    printf("Count: %d\n", count);
}

int main() {
    counter();  // Output: Count: 1
    counter();  // Output: Count: 2
    counter();  // Output: Count: 3
    return 0;
}

Explanation:

  • count is declared as a static variable inside the counter() function.
  • Even though the function is called multiple times, the value of count persists between calls, and it is not reinitialized to 0 each time the function is executed.

Output:

Count: 1
Count: 2
Count: 3

2. Static Variables at the File Level (Global Static Variables)

When static is used outside a function, it limits the visibility of a global variable or function to the file in which it is declared. This is used for encapsulation and modular programming, as it prevents the variable or function from being accessed by other files (translation units) in the same project.

  • Visibility: A static global variable or function is private to the file and cannot be accessed by other files, even if they are part of the same program.
  • Lifetime: Similar to a non-static global variable, a static global variable exists for the lifetime of the program.

Syntax:

static data_type variable_name;

Example:

// File1.c
#include <stdio.h>

static int secret = 42;  // Static global variable

void print_secret() {
    printf("Secret: %d\n", secret);
}

int main() {
    print_secret();  // Access static variable 'secret'
    return 0;
}
// File2.c
#include <stdio.h>

// Uncommenting the following line will cause a compilation error
// printf("Secret: %d\n", secret);  // Error: 'secret' is not accessible here

int main() {
    return 0;
}

Explanation:

  • The variable secret is declared as static in File1.c, so it can only be accessed within File1.c.
  • If you try to access secret in File2.c, it results in a compilation error because secret is not visible outside File1.c.

3. Static Functions

A function declared as static is limited in scope to the file in which it is defined. This is useful when you want to encapsulate the function and prevent it from being called or linked outside that file.

  • Visibility: A static function is visible only to the functions within the same source file.
  • Lifetime: The function exists for the lifetime of the program, but its visibility is restricted to the current translation unit (file).

Syntax:

static return_type function_name(parameters);

Example:

// File1.c
#include <stdio.h>

static void print_message() {
    printf("Hello from static function!\n");
}

int main() {
    print_message();  // Works fine because print_message is in the same file
    return 0;
}
// File2.c
#include <stdio.h>

// Uncommenting the following line will cause a compilation error
// print_message();  // Error: 'print_message' is not accessible here because it's static

int main() {
    return 0;
}

Explanation:

  • print_message() is declared as a static function in File1.c. It can only be called within File1.c.
  • If you try to call print_message() from File2.c, it results in a compilation error because the function is not visible outside of File1.c.

Summary of the static Keyword’s Behavior:

ContextEffect
Inside a functionThe variable retains its value between function calls and is not reinitialized each time the function is called. The scope is limited to the function.
Outside a functionLimits the visibility of a global variable or function to the current file (translation unit). It is private to that file.
In a function declarationLimits the scope of the function to the file, preventing access from other files (translation units).

Benefits of Using static:

  1. Encapsulation: By limiting the scope of variables and functions, static ensures that they are not accidentally accessed or modified from other parts of the program.
  2. Efficient memory usage: Static variables persist for the duration of the program and do not need to be reinitialized each time a function is called, which can be useful in certain situations (e.g., maintaining state).
  3. Internal linkage: Using static for global variables and functions restricts them to the current translation unit, preventing name conflicts and reducing external dependencies.

Conclusion:

The static keyword in C serves to control the scope and lifetime of variables and functions. It is particularly useful for:

  • Maintaining state in functions between calls (static local variables).
  • Restricting access to global variables and functions within the same file (static at the file level).

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as C interview questions, C interview experiences, and details about various C job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now