Home/Blog/Interview Prep/Top 40 C programming interview questions and answers
Home/Blog/Interview Prep/Top 40 C programming interview questions and answers

Top 40 C programming interview questions and answers

14 min read
Feb 26, 2025
content
Interview questions and answers
Where to go from here

You’re sitting across from the interviewer, and they ask you about the difference between malloc and calloc. Are you ready to explain it confidently? Preparing for a C programming interview can feel daunting, but with the right set of C programming interview questions, you can easily impress hiring managers and demonstrate your skills.

This guide is perfect for beginners looking to break into C programming or seasoned developers brushing up before a technical interview. It covers C programming coding interview questions ranging from beginner to advanced levels. These questions help you solidify your knowledge of C programming concepts, prepare effectively for interviews, and confidently tackle various technical challenges.

Interview questions and answers#

Below, we’ve compiled 40 essential C interview questions with a concise answer to help you review key topics quickly, ensuring you’re well-prepared for interviews. Let’s dive into the frequently asked C coding interview questions to boost your confidence and readiness for technical assessments.

If you are a beginner learning C programming fundamentals, check out Learn C from Scratch to build a solid foundation in the language.

  1. What are the basic data types available in the C programming language?
    The basic data types in C include int for integers, float for single-precision floating-point numbers, double for double-precision floating-point numbers, and char for characters, enabling C to handle basic numerical and character-based data.
    In C, derived and user-defined data types and basic data types offer more flexibility for complex data structures.

    • Derived data types: These include arrays (for storing data collections of the same type) and pointers (for storing memory addresses).

    • User-defined data types: These are defined by the programmer to handle complex data requirements, such as struct (for defining custom structures), union (for creating union types), and enum (for enumerating named integer constants). Additionally, typedef allows aliasing or renaming data types for simplicity and readability.

  1. What is the difference between a structure and a union in C?
    When preparing for C technical questions, understanding the differences between structures and unions is crucial for efficient memory management decisions. The table below highlights the key differences between structures and unions in C:

Feature

Structure

Union

Definition

It’s a data type that allows grouping variables of different data types.

It’s a data type in C that allows grouping variables of different data types, but all members share memory.

Memory Allocation

Each member has its memory allocation.

All members share the same memory location. Only one member can hold a value at a time.

Usage

Useful when each variable needs to maintain its value simultaneously.

Helps conserve memory by utilizing the size of the largest member.

  1. What are enumerations?
    Enumerations (enums) are user-defined data types with named integer constants. They improve code readability by associating meaningful names with numeric values.

  2. What is typedef in C?
    typedef in C is a keyword used to create a new name (or alias) for an existing data type. This improves code readability and makes it easier to manage complex types. For example, you can use typedef to simplify structures, pointers, and arrays.
    Here’s an example:

#include <stdio.h>
typedef unsigned long ulong; // Creating an alias for unsigned long
typedef struct {
int x;
int y;
} Point; // Creating an alias for a structure
int main() {
ulong largeNumber = 123456789; // Using the alias 'ulong'
Point p1; // Using the alias 'Point'
// Assigning values to the Point structure
p1.x = 10;
p1.y = 20;
// Displaying the values
printf("Large number: %lu\n", largeNumber); // %lu for unsigned long
printf("Point coordinates: (%d, %d)\n", p1.x, p1.y);
return 0;
}
  1. What is meant by the scope of a variable?
    The scope of a variable refers to the region in the code where the variable is accessible. In C, the variable scope can be categorized into three types:

    • Block scope, where the variable is accessible only within the defined block.

    • Function scope, where the variable is accessible within the function.

    • File scope, where the variable is accessible throughout the entire file.

  1. What is the difference between local and global variables in C?
    Local variables are defined within a function or block and accessible only there. Global variables are defined outside all functions and accessible from any part of the code, allowing shared data.

  2. What are the static variables in C?
    Static variables maintain their value across function calls and are initialized only once. They have a local scope but persist for the duration of the program, allowing for state retention.

  3. What are the different storage classes in C?
    C has four storage classes:

    • Automatic: Variables are created when a block is entered and destroyed when it exits (default storage class).

    • External: Variables are accessible from other files and declared using the extern keyword.

    • Static: Variables maintain their value even after their scope ends, declared using the static keyword.

    • Register: Variables are stored in the CPU registers for faster access, declared with the register keyword.

  1. How do type casting and type conversion differ from each other?
    Type casting and type conversion both involve changing a variable’s type, but they differ in their methods and purposes:

    • Type casting: This is a manual method where the programmer explicitly converts one data type to another using a cast operator. For example, in C, (int) 3.14 converts the float 3.14 to an integer.

    • Type conversion: The compiler performs this automatic process by implicitly converting one data type to another during operations. For instance, if you add an integer to a float, the integer is automatically converted to a float for the operation.

#include <stdio.h>
int main() {
// Type Casting
float num1 = 3.14;
int castedNum = (int) num1; // Explicitly casting float to int
printf("Type Casting: %f casted to int is %d\n", num1, castedNum);
// Type Conversion
int num2 = 5;
float convertedNum = num2 + 2.5; // Implicitly converting int to float
printf("Type Conversion: %d added to 2.5 is %f\n", num2, convertedNum);
return 0;
}
  1. What are tokens in the C language?
    Tokens are the smallest units in a C code, including keywords (like int), identifiers (variable names), constants (like 10), string literals (like "Hello"), and operators (like +, -).

  2. What do preprocessor directives refer to in C?
    Preprocessor directives are commands that are processed before compilation. They start with #, such as #include for including files and #define for defining macros, allowing code modification before the compilation.

  3. What are header files and their uses?
    Header files contain declarations for functions, macros, and data types. They are included in source files using #include, enabling code reuse and organization by separating interface from implementation.

  4. What are pointers in C programming?
    Pointers are variables that store memory addresses. They enable dynamic memory management, allow for efficient array handling, facilitate function arguments, and enable the creation of complex data structures like linked lists. Some common uses of pointers include:

    • Passing arguments by reference: Allows functions to modify the original value without creating a copy.

    • Accessing elements of an array: Enables efficient indexing and manipulation of array elements.

    • Returning multiple values from functions: Facilitates the return of more than one value from a function by using pointers.

    • Facilitating dynamic memory allocation: Allows for the allocation and deallocation of memory during runtime, improving memory management.

    • Implementing complex data structures: Supports the creation of linked lists, trees, and other data structures that require dynamic connections.

C pointer to a variable
C pointer to a variable
  1. What is dynamic memory allocation in C?
    Dynamic memory allocation allows programs to request memory at runtime using functions like malloc(), calloc(), realloc(), and free(). It provides flexibility for managing memory based  on the program’s needs, which is crucial for handling data structures like linked lists and trees.

  2. What is static memory allocation and dynamic memory allocation?
    Static memory allocation occurs at compile-time, where memory size is fixed. Dynamic memory allocation occurs at runtime, allowing memory size to be defined and modified using functions like malloc() and free().

  3. How do malloc() and calloc() differ in the C programming language?
    malloc() allocates memory of a specified size without initializing it, while calloc() allocates memory for an array of elements and initializes all bits to zero, providing cleaner memory management. Here’s a comparison table highlighting the differences between malloc() and calloc() in C:

Parameter

malloc()

calloc()

Memory Initialization

Allocates uninitialized memory

Allocates and initializes memory to zero

Syntax

ptr = (cast_type*) malloc(size);

ptr = (cast_type*) calloc(n, size);

Parameters

Takes one parameter (total size in bytes)

Takes two parameters (number of blocks and size of each block)

Return Value

Returns a pointer to the allocated memory (or NULL on failure)

Returns a pointer to the allocated memory (or NULL on failure)

Speed

Generally faster due to no initialization

Slightly slower due to zero-initialization

Usage

Suitable when initial values are not needed

Suitable when initializing array or data structures

  1. What are dangling pointers in C programming?
    Effective C interview prep involves understanding critical concepts like memory management to confidently address questions about issues such as dangling pointers. Dangling pointers in C programming refer to pointers that point to a memory location that has been deallocated or freed. Accessing such pointers can lead to undefined behavior, including program crashes or corrupted data.

  2. What are memory leaks in C programming?
    A memory leak in C programming refers to a situation where a program allocates memory dynamically using functions like malloc() or calloc() but fails to release it using free(). This unfreed memory remains inaccessible to the program, even though it is no longer needed. Over time, memory leaks can accumulate, consuming system resources and potentially leading to a situation where the program exhausts available memory. This can result in sluggish performance, crashes, or other unexpected behaviors. It’s crucial to ensure that every memory allocation has a corresponding deallocation to prevent memory leaks.

  3. What is the difference between dangling pointers and memory leaks in C programming?
    Here’s a table comparing dangling pointers and memory leaks in C programming:

Feature

Dangling Pointers

Memory Leaks

Definition

Pointers that point to a memory location after it has been freed.

Memory is allocated dynamically and is not released back to the system.

Cause

Occurs when an object is deleted, but pointers pointing to it remain.

Occurs when dynamically allocated memory is not deallocated.

Impact

It can lead to undefined behavior or crashes when pointers are dereferenced.

Gradually reduces available memory, potentially causing performance issues or application crashes.

Detection

It can be hard to detect and often requires careful tracking of pointer assignments and deallocations.

It can be identified using tools like memory profilers (e.g., Valgrind).

Resolution

Requires careful handling of pointer assignments and nullifying pointers after freeing.

Involves ensuring that all dynamically allocated memory is properly freed after use.

  1. What is the Pointer to Pointer in C?
    A pointer to a pointer in C is a variable that stores the address of another pointer variable. This concept allows for multiple levels of indirection, enabling you to create complex data structures and manage dynamic memory.

For those with prior programming experience, C Programming for Experienced Engineers offers advanced insights and techniques to deepen your C expertise.

#include <stdio.h>
#include <stdlib.h>
int main() {
int value = 42; // A regular integer variable
int *ptr = &value; // Pointer to an integer
int **ptrToPtr = &ptr; // Pointer to a pointer
// Accessing the value using pointer to pointer
printf("Value: %d\n", **ptrToPtr); // Outputs: Value: 42
return 0;
}

  1. What is a macro in C programming language?
    A macro is a preprocessor directive defined using #define that allows substituting a code snippet or constant throughout the program before compilation.

  2. What is the difference between a macro and a function?
    Macros are preprocessor directives that perform inline text substitution, making them faster but lacking type checking. Functions are compiled as is, ensuring type safety and easier debugging, but incur a small overhead for each call.

  3. What is pass-by-reference in functions?
    Pass-by-reference allows functions to receive a reference (address) of a variable rather than a copy of its value. Changes to the parameter within the function affect the original variable.

  4. What is pass-by-value in functions?
    Pass by value is a method of passing arguments to a function in which a copy of the actual parameter’s value is made. This means that changes made to the parameter inside the function do not affect the original variable outside the function.

  5. How do you convert a string to numbers in C?
    You can convert a string to a number using functions like atoi() for integers and atof() for floating-point numbers.

  6. What is the sleep() function?
    The sleep() function pauses the program for a specified duration, measured in seconds. It is used to delay execution, often in loops or for timing control.

  7. What is a volatile keyword?
    The volatile keyword informs the compiler that a variable’s value may change unexpectedly, preventing optimizations that could assume its value remains constant. It is often used with hardware-related variables.

  8. What are command-line arguments in C?
    Command line arguments are parameters passed to a program when it is executed. They can be accessed in C using argc (argument count) and argv (argument vector) parameters of the main function.

  9. What is the use of printf() and scanf() functions in C programming language? Also, explain format specifiers.
    print() outputs formatted text, while scanf() inputs data. Format specifiers like %d, %f, and %s define the data type being printed or read.

  10. What is the difference between getc(), getchar(), getch(), and getche()?
    getc() reads a character from a file stream, getchar() reads a character from standard input, getch() reads a character without echoing it, and getche() reads a character while echoing it to the console.

  11. Mention file operations in C.
    File operations in C include opening files (fopen), reading from files (fread, fgets), writing to files (fprintf, fwrite), closing files (fclose), and error handling using ferror.

  12. Is the expression 3["hello"] valid?
    The expression 3["hello"] is valid in C as this is how array indexing works. In C, a[b] is equivalent to *(a + b), and due to the commutative nature of addition, b[a] is also equivalent to *(b + a). This means the index can appear before or after the array name. Here, "hello" is treated as a pointer to the first character, and adding 3 moves the pointer to the fourth character, l. Thus, 3["hello"] evaluates to the character l.

  13. How is source code different from object code?
    Source code and object code are two distinct stages in the process of programming and compiling:

    1. Source code: Source code refers to human-readable instructions written in a programming language such as C, Python, or Java. A simple C program, like print ("Hello, World!"), is considered source code.

    2. Object code: Object code is the machine-readable code generated by a compiler after processing the source code. It consists of binary instructions that a computer’s processor can execute directly. Object code may also include metadata and is not human-readable.

  14. What is an auto keyword in C?
    The auto keyword in C defines the automatic scope for a variable. Here are some key points about the auto keyword:

    • Default storage class: It is the default storage class for local variables. Declining a variable within a function without specifying a storage class is automatically considered auto.

    • Scope: The scope of an auto variable is limited to the block in which it is declared.

    • Lifetime: The lifetime of an auto variable begins when the block is entered and ends when it is exited.

  1. What are modifiers in C?
    Modifiers in C are keywords used to alter the properties of data types. They allow you to change the size, sign, or other characteristics of variables. The primary types of modifiers in C include:

Modifier

Description

Signed

Indicates that a variable can hold both positive and negative values. This is the default for integer types.

Unsigned

Indicates that a variable can only hold non-negative values. This effectively doubles the maximum value that can be stored by eliminating negatives.

Short

Reduces the size of the variable to store less data. For example, a short int typically occupies 2 bytes.

Long

Increases the size of the variable to store more data. For example, long int typically occupies 4 or more bytes.

Long Long

Extends the size further for storing larger integers. For instance, long long int can usually hold values larger than long int.

  1. What is the difference between #include "..." and #include <...>?
    The #include directive in C includes header files in your program.

    1. The #include "..." form is for user-defined headers. It prompts the compiler to search the current directory before looking in standard include paths.

    2. The #include <...> is reserved for standard library headers, with the compiler directly searching standard system directories. Thus, the choice between these forms helps manage file inclusion based on their locations.

  2. Can you explain what loops are in the C programming language and describe the available loops?


Loops in C are control structures that allow the execution of a block of code multiple times based on a specified condition. The primary types of loops in C include:

    • for loop: Executes a block of code a specific number of times.

    • while loop: Repeats a code block if a specified condition is true.

    • do-while loop: Similar to the while loop, it guarantees at least one execution of the code block before checking the condition.

    • nested loop: A loop placed inside another loop, allowing repeated execution of inner and outer blocks based on their respective conditions.

  1. How can we create an Infinite loop in C?
    An infinite loop in C can be created using any of the loop constructs by ensuring the loop’s terminating condition never becomes true to terminate it. Here’s a C program that demonstrates how to create an infinite loop using different loop constructs:

The following code includes the break statement to prevent the program from running indefinitely.You can remove these lines to create actual infinite loops for testing purposes.

#include <stdio.h>
int main() {
// Infinite loop using for loop
printf("Infinite loop using for loop:\n");
for (;;) {
// Break after 1 iteration to avoid an actual infinite loop
printf("Inside for loop\n");
break; // Remove this line for an actual infinite loop
}
// Infinite loop using while loop
printf("Infinite loop using while loop:\n");
while (1) {
// Break after 1 iteration to avoid an actual infinite loop
printf("Inside while loop\n");
break; // Remove this line for an actual infinite loop
}
// Infinite loop using do-while loop
printf("Infinite loop using do-while loop:\n");
do {
// Break after 1 iteration to avoid an actual infinite loop
printf("Inside do-while loop\n");
break; // Remove this line for an actual infinite loop
} while (1);
return 0;
}
  1. Write a program to convert a number to a string with the help of the sprintf() function in the C library.
    Following is a C program that converts an integer to a string using the sprintf() function from the C standard library:

    1. The program initializes an integer variable number with the value 12345.

    2. An array str is declared to store the resulting string.

    3. The sprintf() function converts the integer to a string format, where %d is a format specifier for integers.

    4. Finally, the resulting string is printed to the console.

#include <stdio.h>
int main() {
int number = 12345; // The number to be converted
char str[20]; // Array to hold the resulting string
// Convert the integer to a string
sprintf(str, "%d", number);
// Print the result
printf("The string representation of the number is: %s\n", str);
return 0;
}
  1. Write a C program with two functions to print the Fibonacci series: One function should use recursion, and the other should use iteration.
    Following is a C program that prints the Fibonacci series using iterative and recursive functions as follows:

    1. printFibonacciRecursive acts as a wrapper for the printFibonacci function. It accepts the number of terms to print and calls the recursive function printFibonacci with the initial values of 0 and 1 as the first two terms of the Fibonacci sequence.

    2. printFibonacci function checks if termsLeft is greater than 0. If so, it prints the firstTerm and recursively calls itself with updated values. The updated values are:

      1. termsLeft - 1 (to reduce the number of terms left to print)

      2. secondTerm (becoming the new first term)

      3. firstTerm + secondTerm (the sum of the two terms, which becomes the new second term)

    3. printFibonacciIterative function prints the Fibonacci sequence iteratively. It initializes two variables, firstTerm and secondTerm, with the first two terms of the Fibonacci sequence (0 and 1, respectively). A for loop is used to iterate through the required number of terms. In each iteration, the function:

      1. Prints the firstTerm.

      2. Calculates the next term as the sum of firstTerm and secondTerm.

      3. Updates firstTerm to secondTerm and secondTerm to the newly calculated nextTerm.

#include <stdio.h>
// Function to print the Fibonacci sequence using recursion
// Parameters:
// termsLeft: Number of terms left to print
// firstTerm: The current term in the Fibonacci sequence
// secondTerm: The next term in the Fibonacci sequence
void printFibonacci(int termsLeft, int f irstTerm, int secondTerm) {
if (termsLeft > 0) { // Base condition: Continue if there are terms left to print
printf("%d ", firstTerm);
// Recursive call: Decrease termsLeft and update the terms for the next step
printFibonacci(termsLeft - 1, secondTerm, firstTerm + secondTerm);
}
}
// Wrapper function for the recursive Fibonacci printer
void printFibonacciRecursive(int terms) {
printFibonacci(terms, 0, 1); // Start with 0 and 1 as the first two terms
}
void printFibonacciIterative(int terms) {
int firstTerm = 0, secondTerm = 1; // Initialize the first two terms
// Loop to print the required number of terms
for (int i = 0; i < terms; i++) {
printf("%d ", firstTerm);
int nextTerm = firstTerm + secondTerm; // Calculate the next term
// Update the terms for the next iteration
firstTerm = secondTerm;
secondTerm = nextTerm;
}
}
int main() {
int terms = 15; // Number of Fibonacci terms to print
// Print the Fibonacci sequence using recursion
printf("Recursive version: ");
printFibonacciRecursive(terms);
printf("\n");
// Print the Fibonacci sequence using iteration
printf("Iterative version: ");
printFibonacciIterative(terms);
return 0;
}

Where to go from here#

Mastering C programming fundamentals and exploring its deeper concepts can open the door to various applications in systems programming, embedded software, and more. With consistent practice and working on diverse problems, you’ll sharpen your ability to write efficient, robust code. Building a strong foundation in C will improve your skills and make transitioning to other languages and complex coding challenges easier.

Other than the Learn C from Scratch and C Programming for Experienced Engineers courses, you can explore the following blogs to gain further insights:

Top 5 Advanced C Programming Concepts for Developers
C vs. C++: Core Language Differences Explained

Happy learning!

Frequently Asked Questions

How to prepare for a C coding interview?

To excel in a C coding interview, focus on these key preparation steps:

  1. Master fundamentals: Review core C topics like pointers, memory management, and control structures.
  2. Practice memory management: Understand dynamic memory functions (malloc, calloc, free) and handle pointers safely.
  3. Know key data structures and algorithms: Focus on linked lists, stacks, sorting, searching, and recursion.
  4. Solve common C interview questions: Familiarize yourself with popular C questions, such as recursion, pointer manipulation, memory allocation, and data structures.
  5. Learn system concepts and debugging: Basic OS concepts and tools like gdb are valuable for system-level questions.

What are the commonly asked questions in C?

What are the functions in the C programming language?

What are the four data types of C?

What are pointers in C?


Written By:
Ishrat Fatima
Join 2.5 million developers at
Explore the catalog

Free Resources