Interview Preparation

C Interview Questions

Master the most commonly asked interview questions with comprehensive, expert-crafted answers designed to help you succeed.

25
Questions
100%
Expert Answers
Q1
Why is C called a mid-level programming language?

Due to its ability to support both low-level and high-level features, C is considered a middle-level language. It supports both an assembly-level language, i.e. a low-level language, and a higher-level language. Using asm or __asm__ function, we can write low-level programs, and also, we can write high-level programs using the C syntax. Hence, C is called a mid-level programming language.

Q2
What are the features of the C programming language?

C is a general-purpose, structured programming language that has several powerful features making it suitable for system programming and embedded systems. Below are some of the main features of C:

  • Simple and Efficient: C has a small set of keywords and is easy to learn.
  • Machine Independent: Although C is close to hardware, programs written in C are largely machine-independent.
  • Fast and Powerful: C provides low-level access to memory through pointers and can be optimized for performance.
  • Modular Approach: C supports functions and structured code for modular programming and code reusability.
  • Rich Library: Provides a wide set of built-in functions for handling input/output, strings, memory, etc.
  • Dynamic Memory Allocation: C supports dynamic memory management using malloc(), calloc(), realloc(), and free().
  • Portability: C code can be compiled and run on many different machines with little or no modification.
  • Recursion: C allows function calling itself which is useful in algorithms like DFS, factorial, etc.

Example: A simple C program to demonstrate structure and efficiency:


#include <stdio.h>

int main() {
    int a = 5, b = 10;
    int sum = a + b;
    printf("Sum = %d\n", sum);
    return 0;
}
    
Q3
What are basic data types supported in the C Programming Language?

In the C programming language, basic data types are the fundamental building blocks used to declare variables and allocate memory. These types determine the kind of data a variable can hold, such as integers, characters, or floating-point numbers. Below are the main basic data types supported in C:

  • int – Used to store integer values (e.g., 1, 10, -20).
  • char – Used to store single characters (e.g., 'a', 'Z').
  • float – Used to store single precision decimal numbers (e.g., 3.14, -2.5).
  • double – Used to store double precision floating-point numbers.
  • void – Represents the absence of type, often used for functions that do not return a value.

Example: Declaration of variables using basic data types in C:


#include <stdio.h>

int main() {
    int age = 21;
    char grade = 'A';
    float pi = 3.14f;
    double large_pi = 3.1415926535;
    
    printf("Age: %d\n", age);
    printf("Grade: %c\n", grade);
    printf("Float PI: %.2f\n", pi);
    printf("Double PI: %.10f\n", large_pi);
    
    return 0;
}
    
Q4
What do you mean by the scope of the variable?

Scope in a programming language refers to the region or block of code where a variable is declared and is valid to use. Outside of this region, the variable ceases to exist or becomes inaccessible. In simple terms, the scope of a variable defines its lifetime and visibility within the program.

There are three primary types of variable scopes in C:

  • Local Variables: Declared inside a function or block and accessible only within that function or block.
  • Global Variables: Declared outside all functions and accessible from any function within the same file.
  • Formal Parameters: Variables declared as function parameters; they are treated as local to that function.

Example:


#include <stdio.h>

// Global variable
int globalVar = 10;

void function(int formalParam) {
    // Local variable
    int localVar = 5;
    
    printf("Global: %d\n", globalVar);
    printf("Formal Param: %d\n", formalParam);
    printf("Local: %d\n", localVar);
}

int main() {
    function(3);
    return 0;
}
    

This example demonstrates the usage and boundaries of global, local, and formal parameter variables in C.

Q5
What is the difference between #include <stdio.h> and #include “file.h”?

In C programming, the #include directive is used to include header files. The way you include the file determines where the compiler looks for it.

  • #include <stdio.h>: This is used to include standard library header files. The compiler searches for stdio.h only in the system’s predefined library directories.
  • #include "file.h": This is used to include user-defined header files. The compiler first searches for file.h in the current directory. If it doesn’t find it there, it then searches the system directories.
Q6
What is the purpose of a main() function in C?

The main() function is the entry point of any C program. It is where program execution begins, and every C program must include it.

The primary purposes of main() are:

  • Acts as the starting point of program execution.
  • Returns an integer value to the operating system (usually 0 for successful execution).
  • Can accept command-line arguments using int argc and char *argv[].

Syntax:


#include <stdio.h>

int main(int argc, char *argv[]) {
    printf("Hello, World!\n");
    return 0;
}
    

Explanation:

  • argc – Argument Count: represents the number of command-line arguments.
  • argv – Argument Vector: an array of strings (character pointers) representing arguments.

Q7
What are preprocessor directives in C?

In C, preprocessor directives are special instructions that are processed before the actual compilation of the code begins. These directives start with the # symbol and are handled by the preprocessor. Their primary function is to prepare the code for compilation by performing tasks such as macro substitution, file inclusion, and conditional compilation.

Main types of preprocessor directives include:

  • Macros: Defined using #define to create symbolic constants or functions.
  • File Inclusion: Using #include to include standard or user-defined header files.
  • Conditional Compilation: Using directives like #if, #ifdef, #ifndef, #else, #elif, and #endif to compile code conditionally.
  • Other Directives: Includes #undef (to undefine macros), #pragma (for compiler-specific instructions), etc.

Example:


#include <stdio.h>
#define PI 3.14

int main() {
    printf("Value of PI: %f\n", PI);
    return 0;
}
    

In this example, #define creates a macro for PI, and #include adds the standard I/O library before compilation starts.

Q8
What is the use of static variables in C?

In the C programming language, static variables are used to retain their value across multiple function calls. Unlike regular local variables, which are destroyed once the function exits, static variables preserve their values and exist for the lifetime of the program. They are initialized only once, and if not explicitly initialized, they default to 0.

Static variables are particularly useful when we want to keep track of values between function calls without using global variables.

Example:


#include <stdio.h>

int main() {
    static int var;
    int x;
    printf("Initial value of static variable: %d\n", var);
    printf("Initial value of variable without static: %d", x);
    return 0;
}
    

Note: In the above example, var is initialized to 0 automatically as a static variable, whereas the value of x is garbage because it's a normal local variable without initialization.

Q9
What is the difference between malloc() and calloc() in the C programming language?

In C, both malloc() and calloc() are used for dynamic memory allocation. They are defined in <stdlib.h> and are essential for allocating memory during runtime. However, they differ in syntax, behavior, and initialization.

malloc()calloc()
Allocates a single block of memory of specified size.Allocates multiple blocks of memory and initializes them to zero.
Takes only one argument: total size in bytes.Takes two arguments: number of blocks and size of each block.
Memory is uninitialized (contains garbage values).Memory is initialized to zero.
Faster in performance due to no initialization.Slightly slower because it initializes memory.
Syntax:
int *arr;
arr = (int *)malloc(5 * sizeof(int));
Syntax:
int *arr;
arr = (int *)calloc(5, sizeof(int));
Q10
What are pointers and their uses?

Pointers are variables that store the memory address of another variable or a memory location. They play a vital role in C programming for efficient memory management and manipulation of data structures. Pointers can also be used to refer to other pointer functions, allowing complex operations to be executed efficiently.

The primary goal of using pointers is to save memory space and increase execution speed. They offer powerful features that help manage memory and system resources directly.

Common Uses of Pointers:

  • To pass arguments by reference: Enables functions to modify actual variables passed to them.
  • For accessing array elements: Pointers allow traversal and manipulation of arrays efficiently.
  • To return multiple values: Functions can return multiple values using pointer arguments.
  • Dynamic memory allocation: Pointers are essential in allocating and freeing memory using malloc(), calloc(), and free().
  • To implement data structures: Linked lists, stacks, queues, trees, and graphs rely heavily on pointers.
  • To do system-level programming: Pointers are crucial for accessing hardware and memory addresses directly.
Q11
What do you mean by dangling pointers and how are dangling pointers different from memory leaks in C programming?

In C programming, both dangling pointers and memory leaks are related to improper memory management, but they represent different problems:

Dangling Pointer

A dangling pointer is a pointer that continues to reference a memory location after the object it points to has been deallocated. Accessing a dangling pointer leads to undefined behavior and may cause program crashes or corrupted data.

Example:

int *ptr = (int *)malloc(sizeof(int));
*ptr = 5;
free(ptr);  // Memory is deallocated
// ptr is now a dangling pointer
*ptr = 10;  // Undefined behavior!

Memory Leak

A memory leak occurs when dynamically allocated memory is not properly deallocated using free(). The program continues to consume memory, eventually leading to system memory exhaustion.

Example:

void leakExample() {
    int *leak = (int *)malloc(100 * sizeof(int));
    // forgot to call free(leak);
    // memory is lost, leads to a leak
}
Q12
What is the difference between a compiler and an interpreter? Why is C a compiled language?

Compiler: A compiler is a program that translates the entire source code of a program into machine code (or intermediate code) before execution. It processes the whole code at once and generates an executable file. This leads to faster execution since the code is already translated.

Interpreter: An interpreter reads the source code line by line and executes it directly. It does not produce a separate executable file. This usually makes execution slower compared to compiled languages, but it's useful for scripting and dynamic execution.

C is considered a compiled language because it requires a compiler (like GCC) to convert C source code into machine-level code before the program can run. This process results in faster performance and optimized code execution. The resulting executable is also platform-dependent, meaning code compiled on one system may not work on another without recompilation.

Q13
What is typedef in C?

In C programming, typedef is a keyword that defines an alias for an existing type. Whether it is an integer variable, function parameter, or structure declaration, typedef will shorten the name.

Syntax:

typedef <existing-type> <alias-name>;
    

Here,

  • existing type is already given a name.
  • alias name is the new name for the existing variable.

Example:

typedef long long ll;
    
Q14
What is the difference between macro and functions?

A macro is a name given to a block of C statements defined using a preprocessor directive. Macros are preprocessed, which means all macros are expanded before the compilation phase. On the other hand, functions are compiled and executed during runtime, not during preprocessing.

The key differences between macros and functions are outlined below:

Macro Function
Macros are preprocessed. Functions are compiled.
Code length is increased using macro. Code length remains unaffected using function.
Execution speed using a macro is faster. Execution speed using function is slower.
The macro name is replaced by its value before compilation. Transfer of control takes place during function call.
Macro doesn't check any compile-time errors. Function checks compile-time errors.
Q15
How to convert a string to numbers in C?

In C, we can convert strings to numeric values using several standard library functions. The most common methods include:

  • Using sscanf(): This function reads data from a string, similar to how scanf() reads from standard input.
  • Using atoi(): Stands for ASCII to integer. It converts a string literal or character array to an integer.
  • Using stoi() (C++ only): In C++, the stoi() function from the <string> library can convert a string to an integer.

Example using sscanf():


#include <stdio.h>

int main() {
    char str[] = "1234";
    int num;
    sscanf(str, "%d", &num);
    printf("Number: %d", num);
    return 0;
}
    

Example using atoi():


#include <stdlib.h>
#include <stdio.h>

int main() {
    char str[] = "4567";
    int num = atoi(str);
    printf("Number: %d", num);
    return 0;
}
    

These methods are useful when parsing strings from user input, files, or command-line arguments.

Q16
What is the difference between structure and union?

Both structures and unions are user-defined data types in C that group different types of variables under a single name. However, there are significant differences in how they manage memory and store data. Here's a comparison:

Structure Union
Each member has its own memory location. All members share the same memory location.
Memory required is the sum of all members' sizes. Memory required is equal to the size of the largest member.
Can store values in all members at once. Can store value in only one member at a time.
Syntax:
struct Sample {
  int x;
  float y;
};
Syntax:
union Sample {
  int x;
  float y;
};
Q17
What is the purpose of the volatile keyword in C? How does it prevent compiler optimizations?

The volatile keyword in C tells the compiler that a variable's value can be changed at any time — without any action being taken by the code the compiler finds nearby. This usually occurs in scenarios involving hardware access or asynchronous events like interrupts.

Purpose:

  • Prevents the compiler from optimizing code involving the variable
  • Ensures the program always reads the actual value from memory, not a cached copy
  • Essential when working with hardware registers or flags that may change unexpectedly

Example:


#include <stdio.h>

volatile int flag = 0;

void someFunction() {
    while (flag == 0) {
        // wait for flag to change externally
    }
    printf("Flag changed!\n");
}

    

Explanation: Without volatile, the compiler might optimize the loop by reading flag just once and assuming it doesn't change, causing an infinite loop. volatile ensures that flag is read from memory every time the loop is checked.

Q18
What is the difference between structure and union?

Both structures and unions are user-defined data types in C that group different types of variables under a single name. However, there are significant differences in how they manage memory and store data. Here's a comparison:

Structure Union
Each member has its own memory location. All members share the same memory location.
Memory required is the sum of all members' sizes. Memory required is equal to the size of the largest member.
Can store values in all members at once. Can store value in only one member at a time.
Syntax:
struct Sample {
  int x;
  float y;
};
Syntax:
union Sample {
  int x;
  float y;
};
Q19
What is the sleep() function?

The sleep() function in C allows the users to wait for the current thread for a given amount of time.

The sleep() function will pause the present executable for the given duration by the thread, but other operations of the CPU will function properly.

The sleep() function returns 0 if the requested time has elapsed.

Q20
What are enumerations?

In C, enumerations (or enum) are user-defined data types that consist of named integral constants. They enhance code readability and maintainability by assigning names to constant values.

Enums are useful when a variable can only take one out of a small set of possible values. For example, days of the week, directions, or error codes.

Syntax:

enum enumeration_name { constant1, constant2, ... };

Example:

#include <stdio.h>

enum week { Mon, Tue, Wed, Thur, Fri, Sat, Sun };

int main() {
    enum week day;
    day = Wed;
    printf("%d", day);  // Output: 2
    return 0;
}

Output:

2

In the above example, Wed is the third constant, starting from 0. So its value is 2, and that's what gets printed.

Q21
Explain how memory is divided in a C program (stack, heap, text, data segments).

A C program's memory is divided into several well-defined segments, each serving a specific purpose. Understanding these segments is essential for effective memory management and debugging.

  • Text Segment: Also known as the code segment, it contains the executable instructions of the program. This segment is usually read-only to prevent accidental modification of instructions.
  • Data Segment: Stores global and static variables that are explicitly initialized by the programmer. It is further divided into:
    • Initialized Data Segment – for variables with defined initial values.
  • BSS Segment: Stands for "Block Started by Symbol". It contains all uninitialized global and static variables. These are initialized to zero by default at runtime.
  • Heap: This segment is used for dynamic memory allocation. Memory is allocated here using functions like malloc(), calloc(), and must be deallocated using free(). It grows toward higher memory addresses.
  • Stack: Stores local variables, function parameters, return addresses, and control data. It operates in a LIFO (Last In First Out) manner and grows toward lower memory addresses.

Each of these segments plays a critical role in program execution and memory efficiency.

Q22
What is static memory allocation and dynamic memory allocation?

In C programming, memory can be allocated to variables either at compile time or at runtime. Based on this, memory allocation is classified into two types:

Static Memory Allocation Dynamic Memory Allocation
Memory is allocated during compile time. Memory is allocated during runtime (execution time).
Faster allocation as memory comes from the stack. Slower allocation as memory is taken from the heap.
Less efficient compared to dynamic memory allocation. More efficient in terms of memory usage and flexibility.
Typically used in arrays. Typically used in data structures like linked lists.
Q23
What is the difference between getc(), getchar(), getch(), and getche()?

These functions in C are used to read single characters from input, but they differ in terms of behavior and where they read from:

Function Description
getc() Reads a single character from a specified input stream. Returns ASCII value on success or EOF on failure.
char c = getc(stdin);
getchar() Reads a character from standard input (stdin). Equivalent to getc(stdin).
getch() Reads a character directly from the keyboard without echoing it to the screen. Requires conio.h.
getche() Similar to getch() but echoes the character immediately on the output screen as you type. Also requires conio.h.

Note: getch() and getche() are non-standard and may not work in modern compilers like GCC or Clang. They are mostly used in old compilers like Turbo C.

Q24
What is the use of an extern storage specifier?

The extern keyword in C is used to declare a global variable or function in another file. It tells the compiler that the variable or function exists, but is defined elsewhere (usually in another source file).

Purpose: It extends the visibility of variables and functions across multiple files, enabling modular programming.

Example:


// file1.c
int count = 10;

// file2.c
extern int count;
#include <stdio.h>

int main() {
    printf("%d", count); // Will print 10
    return 0;
}
    

In this example, count is defined in file1.c and accessed in file2.c using the extern keyword.

Q25
What is the use of printf() and scanf() functions in C Programming language? Also, explain format specifiers.

In C programming, printf() and scanf() are standard input-output functions used to display output and take input from the user, respectively.

1. printf() Function

The printf() function is used to display output to the console. It prints the value of variables according to the specified format.

Syntax:

printf("%X", variable_of_X_type);

2. scanf() Function

The scanf() function reads input from the console and stores it in the specified variable(s) based on the format specifier.

Syntax:

scanf("%X", &variable_of_X_type);

3. Format Specifiers in C

Format specifiers are used to indicate the type of data for input/output operations. They help the compiler understand what kind of data to expect.

Specifier Description
%c Character format specifier used to display and scan a character.
%d, %i Signed integer format specifier used for reading and writing integers.
%f, %e, %E Floating-point format specifiers for reading/writing float values.
%s Used for string input/output operations.
%p Used to print memory addresses (pointers).

These specifiers ensure that the data types used in the program are properly interpreted and handled during I/O operations.

Why Choose Our Question Bank?

Get access to expertly crafted answers and comprehensive preparation materials

Complete Collection

Access all 25 carefully curated questions covering every aspect of C interviews

Expert Answers

Get detailed, professional answers crafted by industry experts with real-world experience

Instant Access

Start preparing immediately with instant access to all questions and answers after sign-up