Basic C Interview Questions and Answers

1. What is C language?

  • C is a general-purpose programming language that was developed by Dennis Ritchie in 1972 at Bell Labs.
  • It is widely used for system programming, developing operating systems, and embedded programming.
  • C is known for its efficiency, flexibility, and portability. The language supports structured programming, low-level memory manipulation, and modular programming through functions.
  • It is considered the foundation for many modern languages like C++, Java, and Python.
  • C is commonly used in scenarios where performance and hardware control are crucial.

2. What are the key features of C language ?

C provides several key features that make it powerful and popular.

  • It is a structured language that supports functions and modularity, making code reusable and organized.
  • C is highly portable, meaning programs written in C can run on different platforms with minimal modification.
  •  C is efficient because it provides low-level access to hardware while maintaining high-level constructs.
  • It supports dynamic memory allocation using malloc() and free().
  • Additionally, C is widely used in system programming, including OS development.

3. What is a pointer in C?

  • A pointer in C is a variable that stores the address of another variable. This allows you to directly access and manipulate memory.
  • Pointers are used in various scenarios such as dynamic memory allocation, passing arguments to functions by reference (instead of by value), and handling arrays.
  • A pointer must be declared with a type (e.g., `int *ptr`) to indicate the type of data it points to, and dereferencing the pointer (`*ptr`) allows access to the value stored at the memory address it points to.

4. What is the difference between "++i" and "i++"?

  • Both "++i" and "i++" are increment operators, but they differ in how they operate. "++i" is the pre-increment operator.
  • It increments the value of 'i' first and then returns the incremented value. In contrast, "i++" is the post-increment operator.
  • It returns the current value of 'i' first and then increments it.
  • The difference becomes significant when these operators are used in expressions, but in isolation, there’s no notable performance difference in modern compilers.

5. What is a structure in C ?

  • A structure in C is a user-defined data type that groups related variables of different data types under one name.
  • Each variable within the structure is called a "member" or "field". Structures allow you to represent complex data entities like a record (e.g., a 'student' with fields such as name, age, and marks).
  • The syntax for a structure declaration is `struct

structure_name {

data_type member1;

data_type member2;

};`

and you can access members using the dot operator (e.g.,`student.name`).

6. Explain the difference between 'malloc()' and 'calloc()' functions?

  • Both 'malloc()' and 'calloc()' are used to allocate memory dynamically at runtime, but they have key differences.
  • 'malloc()' allocates a block of memory of the specified size, but it doesn't initialize the memory; the memory block contains garbage values.
  • In contrast, 'calloc()' allocates memory for an array of elements and initializes each element to zero.
  • The 'calloc()' function takes two arguments: the number of elements and the size of each element (`calloc(n, size)`).
  • For example, `malloc(10 * sizeof(int))` allocates memory for 10 integers, while `calloc(10, sizeof(int))` does the same but initializes the memory to zero.

7. What is the purpose of the 'static' keyword in C?

  • The 'static' keyword serves two main purposes in C. When used inside a function, it makes the local variable persist between function calls.
  • Normally, local variables are destroyed when the function exits, but a static local variable retains its value between function calls
  • When used outside of a function, it restricts the visibility of a function or variable to the file in which it is declared, making it private to that file and preventing external files from accessing it.
  • This is useful for maintaining encapsulation and avoiding name conflicts across files.

8. What is the difference between a stack and a heap in memory allocation?

  • The stack and heap are two types of memory used in C programs, each serving different purposes.
  • The stack is used for static memory allocation, where local variables and function call information (e.g., return address) are stored.
  • The memory in the stack is automatically allocated and deallocated as functions are called and returned, and it follows a Last In First Out (LIFO) order.
  • The heap, on the other hand, is used for dynamic memory allocation. Memory in the heap is manually allocated and deallocated using functions like 'malloc()' and 'free()'. Unlike the stack, the heap does not follow LIFO, and memory remains allocated until it is explicitly freed, which gives the programmer more control but also requires more responsibility.

9. What is a dangling pointer?

  • A dangling pointer occurs when a pointer continues to point to a memory location that has been deallocated or freed.
  • This typically happens when a pointer is freed but not set to NULL, or when a pointer goes out of scope but remains in use.
  • Dereferencing a dangling pointer results in undefined behavior, and in worst cases, can cause segmentation faults or memory corruption.
  • To avoid dangling pointers, it is a common practice to set a pointer to NULL after freeing it (`ptr = NULL;`).

10. What is the difference between 'struct' and 'union' in C?

  • A 'struct' and a 'union' are both user-defined data types in C, but they differ in how memory is allocated for their members. In a 'struct', each member has its own memory location, and the total size of the structure is the sum of the sizes of its members.
  • In a 'union', all members share the same memory location, meaning only one member can hold a value at any given time, and the size of the union is the size of its largest member.
  • A 'struct' is used when you need to store multiple related data items simultaneously, whereas a 'union' is useful when you need to store different types of data but only need to access one at a time.

11. What is recursion in C ?

  • Recursion in C refers to the process where a function calls itself in order to solve a problem.
  • Recursive functions break down complex problems into simpler subproblems.
  • A well-designed recursive function must have a base case that stops the recursion, otherwise it will result in infinite recursion and eventually a stack overflow.
  • For example:The classic recursive function for calculating the factorial of a number `n` is: 
objective-c
int factorial(int n) { if (n == 0) return 1; // Base case return n * factorial(n - 1); // Recursive case }

12. What is a memory leak in C ?

  • A memory leak occurs when dynamically allocated memory (using functions like 'malloc()' or 'calloc()') is not freed after it is no longer needed.
  • As a result, the memory is "lost" and cannot be reclaimed, which can lead to a gradual decrease in available memory, causing the system to slow down or crash.
  • To prevent memory leaks, it's crucial to always free memory using the 'free()' function when it's no longer needed and avoid allocating memory unnecessarily.

13. What is the difference between '==' and '===' in C?

  • In C, the '==' operator is used for comparison, while the '===' operator does not exist.
  • The '==' operator compares the values of two variables or expressions.
  • The '===' operator is commonly found in languages like JavaScript, where it checks both value and type.
  • In C, since '==' only checks values, type mismatches can still be compared, and type casting might be needed for certain comparisons between different data types.

14. What is a segmentation fault?

  • A segmentation fault (segfault) is a type of runtime error that occurs when a program tries to access a memory location that it is not allowed to access, such as dereferencing a NULL pointer, accessing memory out of bounds, or writing to read-only memory.
  • Segmentation faults are typically caused by bugs in the program and can be detected using debugging tools like `gdb` or `valgrind` to identify invalid memory accesses.

15. Explain the use of 'typedef' in C.

  • The 'typedef' keyword in C is used to create an alias for an existing data type.
  • This can make code more readable, especially when dealing with complex data types.
For example:
if you want to create a pointer to an integer and use it throughout your program, you can define a typedef:
objective-c
typedef int* IntPtr; IntPtr ptr1, ptr2; // ptr1 and ptr2 are both pointers to integers
This simplifies declarations and enhances code clarity.

16. What is the purpose of the 'return' statement in a function?

  • The 'return' statement is used to exit a function and optionally return a value to the caller.
  • It allows the function to complete its execution and send a result back.
  • If the function is declared with a return type, the 'return' statement must return a value of that type. If the function is of type `void`, no value needs to be returned.
For example:

objective-c
int add(int a, int b) { return a + b; // Returns the sum of a and b }

17. How does a function pass parameters in C?

  • In C, a function can pass parameters in two ways: pass-by-value and pass-by-reference.
  • In pass-by-value, the function gets a copy of the variable's value, and changes to the parameter do not affect the original variable.
  • In pass-by-reference, the function receives a pointer to the variable, allowing it to modify the original variable.
  • For example, passing an array to a function is usually done by reference, as arrays are passed as pointers:
objective-c
void modifyArray(int arr[]) { arr[0] = 100; // Modifies the original array }

18. What is an array in C?

  • An array in C is a collection of variables of the same type, stored in contiguous memory locations. Arrays are indexed from zero, and their size is fixed at compile time.
  • Arrays provide an easy way to store multiple values of the same type, and they are widely used for tasks like storing lists, matrices, or sequences of values.
  • Arrays can be passed to functions by reference, which is efficient for large data sets:
Example
objective-c
int arr[5] = {1, 2, 3, 4, 5}; // Declare an array of 5 integers

19. What is the 'const' keyword used for in C?

  • The 'const' keyword in C is used to define variables whose values cannot be modified after initialization.
  • It is used to improve code safety by ensuring that certain values remain constant throughout the program.
  • This can help avoid accidental changes and make the code easier to maintain.
  • 'const' can also be used with pointers to create constant pointers or pointers to constant data:
objective-c
const int x = 10; // x cannot be modified const int *ptr = &x; // ptr points to a constant value

20. Explain the difference between 'exit()' and '_exit()' functions?

  • The 'exit()' function in C is used to terminate a program and perform standard cleanup operations, such as flushing output buffers, closing open files, and freeing memory.
  • It ensures that resources are released properly before the program terminates.
  • The '_exit()' function, on the other hand, terminates the program immediately without performing any cleanup operations.
  • It is often used in low-level system programming or when the program needs to exit without waiting for the cleanup process.

21. What is a NULL pointer?

  • A NULL pointer is a pointer that does not point to any valid memory location.
  • It is used to indicate that the pointer is not assigned to any object or array. Dereferencing a NULL pointer results in undefined behavior, which is why NULL pointers are commonly used as error indicators.
  • In C, a pointer is typically set to NULL when it is initialized to ensure that it doesn't accidentally point to an invalid memory location:
objective-c
int *ptr = NULL;

22. What is the difference between '++i' and 'i++' in terms of performance?

  • While both '++i' and 'i++' increment the value of 'i', '++i' increments first and then uses the value, while 'i++' uses the current value before incrementing.
  • The performance difference between the two is minimal and generally not noticeable in modern compilers.
  • However, in cases where the increment is part of a more complex expression, '++i' may offer slight advantages due to its earlier increment. For simple cases, either form is functionally equivalent.

23. What are function pointers in C?

  • Function pointers are pointers that point to a function instead of a variable. They allow you to pass functions as arguments to other functions, return functions from functions, and implement callback mechanisms.
  • Function pointers are commonly used in systems programming, event-driven architectures, or when writing generic functions that can operate on various callback functions:
objective-c
int add(int a, int b) { return a + b; } int subtract(int a, int b) { return a - b; } int (*operation)(int, int); // Declare a function pointer operation = add; // Assign the function pointer printf("%d", operation(3, 4)); // Call the function through the pointer

24. What is a macro in C?

  • A macro in C is a preprocessor directive that defines a code fragment, which is then substituted by the preprocessor during compilation.
  • Macros are defined using the `#define` directive.
  • They are commonly used for constant values, inline functions, or to simplify complex expressions:
objective-c
#define PI 3.14 #define MAX(a, b) ((a) > (b) ? (a) : (b))

While macros are useful, they should be used carefully since they can lead to unexpected behaviors due to lack of type checking.

25. What are the different types of operators in C?

C has several types of operators, including: 
  • Arithmetic operators : Used for basic math operations(`+`, `-`, `*`, `/`, `%`).
  • Relational operators: Used to compare values (`==`, `!=`, `>`, `<`, `>=`, `<=`). 
  • Logical operators: Used for logical operations (`&&`, `||`, `!`). 
  • Bitwise operators : Used for bit manipulation (`&`, `|`, `^`, `~`, `<<`, `>>`). 
  • Assignment operators : Used to assign values (`=`, `+=`, `-=`, `*=`, `/=`). 
  • Increment/decrement operators : Used to increment or decrement a variable (`++`, `--`). 
  • Others : Such as `sizeof`, conditional (`? :`), and comma operators.
line

Copyrights © 2024 letsupdateskills All rights reserved