Top 40 C Programming Interview Questions & Answers 👔
Mentor's Note: Technical interviews and college viva sessions don't just check if you can write code; they test if you understand what happens under the hood. You need to know how C manages system memory, how compilers process variables, and where pointers reference data. This guide compiles 40 essential C questions, complete with concise answers and illustrations. Study these to stand out from the crowd! 💡
📚 Exam & Board Focus: This guide is ideal for Class 12 CBSE/GSEB CS practicals and BCA/B.Tech sem-1 viva exams. It focuses on the technical details that examiners check to grade your understanding.
By the end of this tutorial, you'll know:
- 10 foundational questions about C syntax and compilation.
- 10 questions on memory management, pointers, and memory layout.
- 10 questions on control flow, recursion, and functions.
- 10 questions on arrays, strings, and advanced pointer concepts.
📂 Section 1: C Basics & Compilation (1-10)
1. What is C and why is it called a mid-level language?
C is a general-purpose programming language developed by Dennis Ritchie. It is called a mid-level language because it combines the best parts of high-level languages (like structured syntax and readability) with the low-level capability to access hardware, registers, and memory addresses directly.
2. What is the difference between a compiler and an interpreter?
A compiler translates the entire source code into machine code at once, creating an executable file (like .exe or .out) before running it. An interpreter translates and executes the source code line-by-line at runtime, which is slower but makes debugging easier.
3. What is the purpose of header files like #include <stdio.h>?
Header files contain declarations for library functions, macros, and types. Including <stdio.h> tells the compiler about functions like printf() and scanf(), ensuring their signatures match and helping prevent compilation errors.
4. What are keywords in C? Can we use them as variable names?
Keywords are reserved words that have predefined meanings in the C compiler (e.g., int, return, if). You cannot use keywords as variable names because doing so confuses the compiler's syntax analyzer and results in a syntax error.
5. Explain the compilation process of a C program.
The compilation process consists of four main stages:
- Preprocessing: Cleans up comments and expands macros/includes.
- Compilation: Translates preprocessed code into assembly code.
- Assembly: Converts assembly code into object code (
.objor.o). - Linking: Combines object code files with library code to create the final executable file.
6. What is the difference between local and global variables?
- Local Variables: Declared inside a function or block, stored on the stack, and accessible only within that block.
- Global Variables: Declared outside all functions, stored in the data segment, and accessible by any function in the program.
7. What are static variables in C?
Static variables are declared using the static keyword. They retain their value between function calls and are initialized only once. They persist for the entire lifetime of the program but are visible only within the function or file they are declared in.
void counter() {
static int count = 0; // Initialized once
count++;
printf("%d ", count);
}
8. What is the difference between variable definition and declaration?
- Declaration: Introduces a variable name and its data type to the compiler, allocating no memory (e.g.
extern int a;). - Definition: Allocates memory and sets aside storage space for the variable (e.g.
int a;orint a = 10;).
9. Explain the use of the const qualifier.
The const qualifier prevents a variable's value from being modified after initialization. If you attempt to change a constant variable's value later in the code, the compiler will throw a compile-time error.
const double PI = 3.14159;
// PI = 3.14; // Throws a compile-time error
10. What is a preprocessor directive?
A preprocessor directive is a command starting with # (like #define or #include) that instructs the compiler's preprocessor to modify the source code text before actual compilation begins.
📂 Section 2: Data Types & Memory Management (11-20)
11. What is the difference between signed and unsigned integers?
- Signed: Uses the most significant bit (MSB) as a sign flag (0 for positive, 1 for negative), allowing both positive and negative values.
- Unsigned: Uses all bits to represent positive values, doubling the maximum positive number that can be stored compared to a signed integer of the same size.
12. What is the size of a pointer in C?
The size of a pointer does not depend on the data type it points to. Instead, it depends on the system architecture: it is 4 bytes on a 32-bit system and 8 bytes on a 64-bit system, which is the size needed to hold a memory address on that platform.
13. What is the difference between malloc() and calloc()?
malloc(): Allocates a single block of memory on the heap and leaves it uninitialized, meaning it contains random garbage values.calloc(): Allocates multiple blocks of memory and automatically initializes all bytes to zero, which is safer but slightly slower.
14. Explain the purpose of realloc().
realloc() changes the size of previously allocated memory on the heap. If possible, it expands or shrinks the existing memory block in place; otherwise, it allocates a new block, copies the existing data over, and automatically frees the old block.
15. What is a memory leak and how do you prevent it?
A memory leak occurs when a program allocates memory on the heap (using malloc or calloc) but fails to release it using free() after it is no longer needed. You can prevent this by ensuring every allocation call has a corresponding free() call when that block of memory goes out of scope.
16. What is a dangling pointer?
A dangling pointer is a pointer that points to a memory address that has already been deallocated or freed. Accessing a dangling pointer can cause your program to crash or produce unpredictable results.
int *ptr = (int*)malloc(sizeof(int));
free(ptr);
// ptr is now a dangling pointer!
ptr = NULL; // Fix: Set to NULL
17. What is a NULL pointer and how is it different from a wild pointer?
- NULL Pointer: A pointer explicitly assigned to point to nothing (usually address
0), which is safe to check before dereferencing. - Wild Pointer: An uninitialized pointer that points to a random address in memory, making it dangerous to dereference.
18. What is the difference between a structure and a union?
- Structure (
struct): Allocates separate memory locations for each member variable. The total size is at least the sum of the sizes of its members. - Union (
union): Share a single memory location among all member variables. The total size is the size of its largest member, meaning only one member can be used at a time.
19. What is structure padding?
Structure padding is when the compiler inserts empty bytes between structure members to align variables with the system's hardware architecture limits. This makes memory access faster, but it also increases the total memory size of the struct.
20. Explain the difference between stack and heap memory.
- Stack: Managed automatically by the CPU. It is fast, structured, and holds local variables and function call frames.
- Heap: Managed manually by the programmer using allocation functions. It is larger, slower to access, and variables persist until explicitly freed.
📂 Section 3: Control Flow & Functions (21-30)
21. What is the difference between break and continue?
break: Immediately terminates the loop orswitchblock and transfers execution to the statement following it.continue: Skips the remaining statements in the current iteration of a loop and moves directly to the next loop iteration check.
22. What happens if a switch case does not have a break statement?
Without a break statement, execution falls through to the next case and runs its statements, regardless of whether that case's condition is met. This behavior is called fall-through.
23. What is recursion and what are its drawbacks?
Recursion is when a function calls itself to solve a smaller version of a problem. Its main drawbacks are that it consumes a large amount of stack memory (due to multiple active function frames) and can cause a stack overflow error if it recursion is too deep.
24. What is the difference between call by value and call by reference?
- Call by Value: Passes a copy of the argument's value to the function. Changes made inside the function do not affect the original variable.
- Call by Reference: Passes the memory address of the argument (using pointers). This allows changes made inside the function to directly update the original variable.
25. Can a function return multiple values in C?
No, a C function can return only one value directly using a return statement. However, you can return multiple values indirectly by passing pointer arguments (call by reference) or by returning a structure containing multiple member variables.
26. What is an inline function?
An inline function is a function defined with the inline keyword. It suggests to the compiler that it replace function calls directly with the function's code, which reduces the overhead of function calls but can increase the final executable file size.
27. What is stack overflow and when does it occur?
Stack overflow occurs when the stack memory runs out of space. This usually happens during deep or infinite recursion, or when you declare excessively large local arrays on the stack instead of using heap allocation.
28. How does exit() differ from return?
return: Exits the current function and returns control to the calling function.exit(): Immediately terminates the entire program, closes open files, flushes buffers, and returns control directly to the operating system.
29. Explain the Ternary operator in C.
The Ternary operator (? :) is a shorthand way to write simple if-else statements. It takes three operands: a condition, an expression to evaluate if the condition is true, and an expression to evaluate if the condition is false.
int max = (a > b) ? a : b;
30. What is the difference between entry-controlled and exit-controlled loops?
- Entry-Controlled (
for,while): Evaluates the loop condition before executing the body. If the condition is false initially, the body does not run. - Exit-Controlled (
do-while): Evaluates the loop condition after executing the body, ensuring the body runs at least once.
📂 Section 4: Arrays, Strings & Pointers (31-40)
31. How are arrays stored in memory?
Arrays are stored in contiguous (sequential) memory locations. The elements are placed one after the other in memory without gaps, allowing index access by offsetting addresses from the starting base address.
32. What is a pointer to a pointer (double pointer)?
A double pointer is a pointer variable that stores the memory address of another pointer variable. It is declared using two asterisks (e.g. int **ptr;) and is commonly used to dynamically allocate 2D arrays or modify pointer values inside functions.
33. Explain the difference between char arr[] and char *ptr for string definition.
char arr[] = "hello";: Allocates a mutable character array on the stack, allowing you to modify individual characters in the string.char *ptr = "hello";: Allocates a string literal in read-only memory and points to it. Attempting to modify its characters will result in a runtime error or crash.
34. What is the purpose of the null terminator \0 in C strings?
The null terminator \0 marks the end of a string in C. Since C does not track string lengths automatically, string functions (like printf and strlen) look for the \0 character to know where to stop reading.
35. What is array decay in C?
Array decay is when an array name automatically converts to a pointer pointing to its first element when passed to a function. When this happens, the array loses its size information, and sizeof returns the size of the pointer rather than the entire array.
36. What is a void pointer (generic pointer)?
A void pointer is a pointer declared using void * that can point to any data type without casting. It must be cast to a specific type before you dereference it. It is commonly used by functions like malloc() to return generic memory allocations.
37. What is a function pointer?
A function pointer is a pointer variable that stores the entry point address of a function in memory. It allows you to pass functions as arguments to other functions or invoke them dynamically.
int (*func_ptr)(int, int) = &add;
int result = func_ptr(5, 10);
38. What is the difference between strcmp() and memcmp()?
strcmp(): Compares two strings character-by-character and stops comparing as soon as it encounters a null terminator\0.memcmp(): Compares a specified number of bytes of memory blocks directly, ignoring null terminators and comparing the raw bytes.
39. Why is the function gets() dangerous, and what is its safe alternative?
gets() is dangerous because it does not check the size of the buffer it is reading into, which can lead to buffer overflow security vulnerabilities. The safe alternative is fgets(), which allows you to specify the maximum number of characters to read.
40. What is a buffer overflow?
A buffer overflow occurs when a program writes more data to a memory buffer than it was allocated to hold. This extra data spills over and overwrites adjacent memory, which can corrupt variables, cause crashes, or be exploited to run malicious code.
🎯 Practice Problems
Easy Level 🟢
- Write a short program that uses a
staticvariable to count how many times a function has been called. - Write a snippet showing structure initialization vs union initialization.
Medium Level 🟡
- Write a function that accepts an array and its size (avoiding array decay size issues) and prints all elements.
- Create a double pointer that dynamically allocates space for a single integer.
Hard Level 🔴
- Write a function pointer implementation that routes calls dynamically to either an
addorsubtractfunction based on user input. - Write a program that intentionally triggers a stack overflow using recursion to demonstrate its mechanics.
❓ Frequently Asked Questions
Q: Is C still relevant when languages like Python and C++ exist?
Yes. C is the language of operating systems (Linux, Windows kernel), database engines (PostgreSQL), embedded systems, and resource-constrained environments where high performance and control over hardware are required.
Q: What is the difference between a pointer and a reference in programming?
A pointer stores a memory address and can be reassigned or set to NULL. A reference (available in languages like C++, but not C) is an alias for an existing variable, cannot be changed after creation, and cannot be null.
Q: What is the difference between undefined behavior and compiler-dependent behavior?
- Undefined Behavior: The C standard does not define what should happen (e.g. dividing by zero). The program might crash, run fine, or corrupt memory.
- Compiler-Dependent: The behavior depends on the compiler or target hardware architecture (e.g. the size of an
int).
✅ Summary
In this reference guide, you've reviewed:
- ✅ 10 core concepts regarding C compilation phases, variables, and scope lifetimes.
- ✅ 10 questions on data memory models, stack vs heap, pointer sizes, and structure layouts.
- ✅ 10 questions on functions, calling conventions, recursion limits, and loop branching.
- ✅ 10 questions on arrays, decay characteristics, string terminations, and buffer safety.
💡 Board Viva Advice 👔
- Pointer Dereferencing: Always check pointers for
NULLbefore dereferencing them in front of an examiner (if (ptr != NULL)). - Compilation Steps: Be ready to list the compilation steps in order: Preprocessor -> Compiler -> Assembler -> Linker.
📚 Further Reading
Continue your learning path:
Go deeper: