Top 35 C Programming Interview Questions and Answers
Feb 26, 2026 9 Min Read 60851 Views
(Last Updated)
C programming, often hailed as the “mother of all languages,” remains a cornerstone of software development. Whether you’re coding embedded systems, designing operating systems, or delving into low-level programming, mastering C is non-negotiable.
With its efficiency, simplicity, and unparalleled control over hardware, C is a must-know language for every aspiring and experienced developer.
To help you prepare for your next technical interview, we’ve compiled 35 essential C programming interview questions and answers, ranging from beginner to advanced. This guide is your one-stop resource to ace your interview and stand out as a C programming expert.
Quick Answer:
C programming interviews test your grasp of fundamentals, coding logic, and low-level concepts. Focus on pointers, arrays, strings, memory allocation, data structures, file handling, and bitwise operations. Be ready to explain code, optimize algorithms, and solve problems efficiently, as interviewers want to see both your technical knowledge and your approach to writing clean, reliable C programs.
Table of contents
- How to Prepare for a C Programming Interview?
- Beginner Level C Programming Interview Questions and Answers
- What is C and why is it called a middle-level language?
- What are the basic data types in C?
- What is the difference between #include <stdio.h> and #include "file.h"?
- What is the purpose of main() in C?
- What is the difference between printf() and scanf()?
- What are data types in C?
- What are storage classes in C?
- What is the const keyword in C?
- How does sizeof work in C?
- What is the difference between a compiler and an interpreter? Why is C compiled?
- Intermediate Level C Programming Interview Questions and Answers
- What are pointers in C?
- What is a dangling pointer? How do you prevent it?
- What is the difference between call by value and call by reference?
- What is the difference between malloc(), calloc(), and realloc()?
- What is recursion? How does it differ from iteration?
- What is a struct in C, and how does it differ from a union?
- Some Interesting Facts:
- What is the difference between a shallow copy and a deep copy?
- What is memory alignment and padding in C structs?
- What are function pointers? How are they used?
- Advanced Level C Programming Interview Questions and Answers
- What is undefined behavior in C? Why must you avoid it?
- What is the volatile keyword? When do you use it?
- How is memory divided in a running C program?
- What is a segmentation fault, and how does it occur?
- What is the difference between exit() and _exit()?
- What are macros? How do they differ from inline functions?
- What is a reentrant function?
- What is #pragma in C?
- What is the difference between fgets() and gets() for reading strings?
- What is the difference between C89, C99, and C11?
- Tricky Output Questions
- What is the output?
- What is the output?
- What is the output?
- What is the output?
- What is the output?
- Common C Interview Mistakes to Avoid
- Conclusion
How to Prepare for a C Programming Interview?
Study in this order: fundamentals → memory model → pointers → data structures → tricky output questions → coding problems.
Practical 2-week roadmap:
- Days 1–3: Data types, operators, control flow, functions, scope and storage classes
- Days 4–6: Pointers, arrays, strings, pointer arithmetic
- Days 7–9: Dynamic memory (malloc, calloc, realloc, free), memory segments
- Days 10–11: Structs, unions, enums, bitwise operations
- Days 12–13: File I/O, preprocessor directives, macros
- Day 14: Output-based tricky questions and past company interview questions
Beginner Level C Programming Interview Questions and Answers
This section checks whether your foundations are actually solid. Expect questions about syntax, data types, operators, input/output, and how a basic C program runs. Interviewers aren’t trying to trick you here, they’re making sure you understand what your code is doing instead of memorizing patterns.
1. What is C and why is it called a middle-level language?
C programming is a compiled, procedural language that sits between assembly (low-level) and languages like Python (high-level). It gives you hardware-level control , direct memory access, and pointer arithmetic while still supporting structured programming with functions, loops, and conditionals. This makes it ideal for operating systems, compilers, and embedded systems.
2. What are the basic data types in C?
| Data Type | Purpose | Example |
| int | Integer values | int a = 5; |
| char | Single character | char b = ‘A’; |
| float | Single-precision decimal | float c = 3.14; |
| double | Double-precision decimal | double d = 3.14159; |
| void | No value / no type | void func() {} |
On a 64-bit system: int = 4 bytes, char = 1 byte, float = 4 bytes, double = 8 bytes.
3. What is the difference between #include <stdio.h> and #include “file.h”?
- #include <stdio.h> , angle brackets tell the compiler to look only in the system’s standard library directories.
- #include “file.h” , quotes tell the compiler to look in the current directory first, then fall back to system directories.
Use < > for standard library headers. Use ” ” for your own custom header files.
4. What is the purpose of main() in C?
main() is the mandatory entry point of every C program , execution always starts here. It returns an int (0 signals successful execution to the OS). It can accept command-line arguments via int argc (count) and char *argv[] (values). Every valid C program must have exactly one main() function.
5. What is the difference between printf() and scanf()?
- printf() outputs formatted text to the console. Format specifiers: %d (int), %f (float), %s (string), %c (char).
- scanf() reads formatted input from the keyboard. Always requires the address of the variable using &.
int x;
printf("Enter a number: ");
scanf("%d", &x); // & is mandatory , passes the address of x
printf("You entered: %d", x);
A common beginner mistake: forgetting & in scanf(), which causes undefined behavior.
6. What are data types in C?
Keywords in C are reserved words with fixed meanings; they cannot be used as variable or function names. C89 defines 32 keywords; C99 added 5 more. Most-tested:
| Keyword | Purpose |
| int, char, float | Declare data types |
| if / else | Conditional branching |
| while, for | Loops |
| return | Exit function, return value |
| struct | Define composite type |
| static | Retain value across function calls |
| const | Mark variable as read-only |
7. What are storage classes in C?
A storage class defines a variable’s scope, lifetime, and default initial value. There are four:
| Storage Class | Scope | Lifetime | Default Value |
| auto | Local block | Until block ends | Garbage |
| register | Local block | Until block ends | Garbage |
| static | Local or file | Entire program | 0 |
| extern | Global (across files) | Entire program | 0 |
void counter() {
static int count = 0; // retains value across calls
count++;
printf("%d\n", count);
}
// First call → 1, second call → 2, third call → 3
8. What is the const keyword in C?
const marks a variable as read-only after initialization , the compiler rejects any attempt to modify it. It improves safety and communicates intent clearly to other developers.
const int MAX = 100; // MAX cannot be changed
const int *ptr = &MAX; // cannot modify the value through ptr
int * const ptr2 = &x; // cannot change where ptr2 points
Interview tip: the position of const relative to * matters. const int *p = can’t modify the value. int * const p = can’t change the pointer address.
9. How does sizeof work in C?
sizeof is a compile-time operator that returns the size in bytes of a type or variable, it has zero runtime overhead.
printf("%zu\n", sizeof(int)); // 4
printf("%zu\n", sizeof(double)); // 8
int arr[10];
printf("%zu\n", sizeof(arr)); // 40
printf("%zu\n", sizeof(arr)/sizeof(arr[0])); // 10 , useful for array length
Primary use: writing portable code that doesn’t hardcode byte sizes, and calculating correct sizes for malloc() calls.
10. What is the difference between a compiler and an interpreter? Why is C compiled?
| Compiler | Interpreter | |
| Process | Translates entire source to machine code before execution | Executes source line-by-line |
| Output | Standalone executable | No separate file |
| Speed | Faster at runtime | Slower at runtime |
| Examples | C, C++, Go | Python (traditional), Ruby |
C uses a compiler (GCC, Clang) because the resulting machine code runs significantly faster, essential for operating systems and embedded firmware where performance is non-negotiable.
C was originally created not as a general-purpose language, but to rewrite the Unix operating system. Before C, Unix was written in assembly , making it tied to one specific processor. Rewriting it in C meant Unix could be ported to different hardware by simply recompiling. That single decision in 1973 made C the backbone of modern computing infrastructure. Today, the Linux kernel, which powers over 90% of the world’s servers, is still written primarily in C.
Looking to move beyond basic ChatGPT skills? Here’s your chance to be a part of Be part of the Bharat AI Initiative, a nationwide movement by HCL GUVI, in association with OpenAI, built to help India’s youth develop advanced ChatGPT skills absolutely free! Learn structured prompting, refine responses with clarity, and apply ChatGPT more effectively in projects, assignments, and everyday work. Learn in English, Hindi, Marathi, Tamil, or Telugu and start your free AI journey!
Intermediate Level C Programming Interview Questions and Answers
Now the focus shifts from writing programs to understanding how they behave in memory. Pointers, structs, dynamic allocation, and function behavior dominate this stage. You’ll need to reason about what happens behind the scenes, not just what the code prints.
11. What are pointers in C?
A pointer is a variable that stores the memory address of another variable. Pointers enable direct memory access, the foundation of dynamic memory allocation, data structures, and efficient parameter passing.
int num = 10;
int *ptr = # // ptr stores the address of num
printf("%d", *ptr); // dereference: prints 10
printf("%p", (void*)ptr); // prints the memory address
12. What is a dangling pointer? How do you prevent it?
A dangling pointer points to memory that has already been freed or gone out of scope. Dereferencing it causes undefined behavior or a crash.
int *ptr = (int *)malloc(sizeof(int));
free(ptr);
*ptr = 10; // DANGER: dangling pointer , memory already freed
// Prevention: NULL the pointer immediately after freeing
free(ptr);
ptr = NULL; // now it's a safe null pointer, not a dangling one
13. What is the difference between call by value and call by reference?
| Call by Value | Call by Reference | |
| What’s passed | A copy of the variable | The address of the variable |
| Modifies original? | No | Yes |
| When to use | When the function shouldn’t alter caller’s data | When the function must update the caller’s variable |
void byValue(int x) { x = 20; } // original unchanged
void byRef(int *x) { *x = 20; } // original modified
int a = 10;
byValue(a); // a is still 10
byRef(&a); // a is now 20
14. What is the difference between malloc(), calloc(), and realloc()?
| Function | Purpose | Initializes Memory? |
| malloc(size) | Allocate size bytes | No , contains garbage |
| calloc(n, size) | Allocate n elements × size bytes | Yes , zero-initialized |
| realloc(ptr, size) | Resize an existing allocation | No |
| free(ptr) | Release allocated memory | N/A |
int *arr = (int *)malloc(5 * sizeof(int));
if (arr == NULL) { exit(1); } // always check!
// use arr...
free(arr);
arr = NULL; // prevent dangling pointer
Always check if the return value is NULL. Always pair every malloc/calloc with a free().
15. What is recursion? How does it differ from iteration?
Recursion is when a function calls itself to solve a smaller sub-problem. Every recursive function needs a base case to stop.
// Recursive factorial
int factorial(int n) {
if (n == 0) return 1; // base case
return n * factorial(n - 1); // recursive call
}
16. What is a struct in C, and how does it differ from a union?
| Struct | Union | |
| Memory | Each member has its own space | All members share the same space |
| Size | Sum of all members (+ padding) | Size of the largest member |
| Access | All members accessible simultaneously | Only one member active at a time |
struct Person { char name[50]; int age; }; // size = 54 bytes (+ padding)
union Data { int i; float f; char s[20]; }; // size = 20 bytes
Use union when a variable needs to hold one of several types at a time , saves memory in embedded systems and protocol parsing.
Some Interesting Facts:
- 70% of C interview questions revolve around memory
Across service companies and product companies, the same themes keep repeating: pointers, arrays vs pointers, dynamic allocation, and undefined behavior. If your memory model is clear, half the interview becomes predictable.
- Output questions matter more than long program
Written rounds (especially TCS, Infosys, Wipro style) rarely ask you to build large programs. Instead, they test reasoning speed. Being able to trace 5–10 lines of code accurately is usually more valuable than knowing 50 library functions.
17. What is the preprocessor in C?
The C preprocessor runs before compilation; it handles file inclusion, macro expansion, and conditional compilation. It never sees types or variables, only text.
| Directive | Purpose | Example |
| #include | Include header file | #include <stdio.h> |
| #define | Define macro or constant | #define PI 3.14159 |
| #ifdef/#endif | Conditional compilation | #ifdef DEBUG |
| #pragma once | Prevent duplicate header inclusion | #pragma once |
Macros have no type safety, prefer const variables and inline functions in C99+ where possible.
18. What is the difference between a shallow copy and a deep copy?
Shallow copy duplicates the pointer (both point to the same memory). Deep copy duplicates the actual data (each has independent memory).
// Shallow , p1 and p2 share the same memory block
struct Person *p2 = p1;
// Deep , p2 has its own independent copy of the data
struct Person *p2 = malloc(sizeof(struct Person));
*p2 = *p1;
Shallow copy is dangerous: modifying one affects the other. Freeing one and accessing the other causes a use-after-free bug.
19. What is memory alignment and padding in C structs?
Compilers insert padding bytes between struct members to ensure each member is aligned to its own size , misaligned access forces the CPU into multiple memory reads, degrading performance.
struct Unoptimized { char a; int b; char c; };
// sizeof = 12 (not 6) , 3 bytes padding after 'a', 3 bytes after 'c'
struct Optimized { int b; char a; char c; };
// sizeof = 8 , ordering from largest to smallest minimizes padding
Rule of thumb: declare struct members from largest to smallest type to minimize wasted space.
20. What are function pointers? How are they used?
A function pointer stores the address of a function, allowing functions to be passed as arguments and called dynamically at runtime.
int add(int a, int b) { return a + b; }
int (*func_ptr)(int, int) = &add; // declare and assign
printf("%d", func_ptr(3, 4)); // call → prints 7
Real-world uses: callbacks (qsort comparator), strategy pattern (swap algorithms without if/else chains), event handlers in embedded systems and GUIs.
Looking to move beyond basic ChatGPT skills? Here’s your chance to be a part of Be part of the Bharat AI Initiative, a nationwide movement by HCL GUVI, in association with OpenAI, built to help India’s youth develop advanced ChatGPT skills absolutely free! Learn structured prompting, refine responses with clarity, and apply ChatGPT more effectively in projects, assignments, and everyday work. Learn in English, Hindi, Marathi, Tamil, or Telugu and start your free AI journey!
Advanced Level C Programming Interview Questions and Answers
Here’s where C becomes a systems language. Topics move into memory layout, undefined behavior, compiler interaction, and low-level execution details. Interviewers use these questions to see if you can write reliable, production-grade code rather than classroom code.
21. What is undefined behavior in C? Why must you avoid it?
Undefined behavior (UB) is any operation the C standard explicitly leaves unpredictable; the compiler can generate any result, including code that appears to work but silently corrupts data.
Common UB examples:
int *ptr = NULL; *ptr = 5; // null pointer dereference
int arr[5]; arr[10] = 1; // out-of-bounds write
int x; printf("%d", x); // uninitialized variable read
int a = INT_MAX; a = a + 1; // signed integer overflow
UB doesn’t always crash immediately; it can produce wrong results silently, create security vulnerabilities, or behave differently across compilers and optimization levels. Avoiding UB is a core professional C discipline.
22. What is the volatile keyword? When do you use it?
volatile tells the compiler that a variable’s value can change at any time from outside normal program flow, never cache it in a register, always re-read from memory.
volatile int sensor = 0;
// Compiler will always read from memory, never use a cached register value
Use cases: hardware registers in embedded/firmware code, variables modified by interrupt service routines (ISRs), and memory-mapped I/O. Without volatile, an aggressive optimizer might convert while (flag == 0) {} into an infinite loop that ignores real memory updates.
23. How is memory divided in a running C program?
A running C program’s memory is divided into five segments:
| Segment | Contents | Managed By |
| Text | Compiled machine code (read-only) | OS |
| Data | Initialized global & static variables | Compiler |
| BSS | Uninitialized global & static variables (zero-filled) | Compiler |
| Heap | Dynamic allocations (malloc, calloc) | Programmer |
| Stack | Local variables, function frames, return addresses | CPU/OS |
Stack grows downward; heap grows upward. Stack overflow occurs when deep recursion exhausts stack space.
24. What is a segmentation fault, and how does it occur?
A segmentation fault is a runtime crash that occurs when a program accesses memory it doesn’t own or isn’t permitted to access.
int *ptr = NULL;
*ptr = 10; // crash: NULL pointer dereference
int arr[5];
arr[10] = 1; // crash: out-of-bounds write
char *str = "hello";
str[0] = 'H'; // crash: write to read-only string literal
Debug with valgrind ./program or compile with -fsanitize=address -g. Segfaults are always a memory access violation , trace back to where the invalid pointer originated.
25. What is the difference between exit() and _exit()?
| exit() | _exit() | |
| Cleanup | Flushes I/O buffers, calls atexit() handlers, closes files | None , terminates immediately |
| Use case | Normal program termination | Child process after fork() to avoid flushing parent’s buffers |
exit(0); // clean shutdown , buffers flushed, handlers called
_exit(0); // immediate termination , no cleanup whatsoever
26. What are macros? How do they differ from inline functions?
| Macros | Inline Functions | |
| Expansion | Preprocessor text substitution | Compiled inline by the compiler |
| Type checking | None | Yes , compiler enforces types |
| Side effects | Can cause bugs with ++/– | Safe |
| Debugging | Harder | Easy , appears in stack traces |
#define SQUARE(x) ((x) * (x)) // MAX(a++) evaluates a++ twice , bug!
inline int square(int x) { return x * x; } // safe, type-checked
Always wrap macro arguments in parentheses. Prefer inline functions in C99+.
27. What is a reentrant function?
A reentrant function can be safely interrupted and called again before its first execution finishes; it produces correct results regardless of concurrent execution.
A function is reentrant if it uses only local variables, calls no non-reentrant functions, and shares no static or global state. Critical for multi-threaded programs and interrupt service routines.
// Non-reentrant: uses static state
char *strtok(char *s, const char *delim); // internal static buffer , not thread-safe
// Reentrant version:
char *strtok_r(char *s, const char *delim, char **saveptr); // caller provides state
28. What is #pragma in C?
#pragma is a compiler-specific directive that gives special instructions to the compiler without changing C language semantics.
#pragma once // prevent duplicate header inclusion (modern guard)
#pragma pack(1) // force struct members with no padding
#pragma GCC optimize("O3") // GCC-specific: maximum optimization level
#pragma once is the modern, cleaner alternative to the traditional #ifndef/#define/#endif header guard pattern.
29. What is the difference between fgets() and gets() for reading strings?
| fgets() | gets() | |
| Buffer limit | Yes , specify max characters | No , reads until newline |
| Safety | Safe | Causes buffer overflow |
| C11 status | Standard | Removed , never use |
fgets(buffer, sizeof(buffer), stdin); // safe: won't overflow buffer
gets(buffer); // NEVER USE , removed from C11, causes security vulnerabilities
gets() was officially removed in the C11 standard because it has caused countless real-world buffer overflow vulnerabilities. Always use fgets().
30. What is the difference between C89, C99, and C11?
| Standard | Key Additions |
| C89/C90 | Original standard. Variables must be declared at top of block. |
| C99 | // comments, bool type, declare variables anywhere, inline, stdint.h, variadic macros |
| C11 | Multi-threading (<threads.h>), _Generic, _Static_assert, anonymous structs/unions, removed gets() |
For most interviews and system work, C99 is the practical baseline. Embedded C projects often target C89 for toolchain compatibility.
Looking to move beyond basic ChatGPT skills? Here’s your chance to be a part of Be part of the Bharat AI Initiative, a nationwide movement by HCL GUVI, in association with OpenAI, built to help India’s youth develop advanced ChatGPT skills absolutely free! Learn structured prompting, refine responses with clarity, and apply ChatGPT more effectively in projects, assignments, and everyday work. Learn in English, Hindi, Marathi, Tamil, or Telugu and start your free AI journey!
Tricky Output Questions
These appear regularly in TCS, Wipro, and Infosys written tests. Try to predict the output before reading the answer.
31. What is the output?
#include <stdio.h>
int main() {
int x = 5;
printf("%d %d %d\n", x++, x++, x++);
return 0;
}
Answer: Undefined behavior. Function argument evaluation order is unspecified in C. You might see 7 6 5, 5 6 7, or anything else depending on the compiler. Never modify a variable multiple times within the same expression.
32. What is the output?
#include <stdio.h>
void foo(int arr[]) {
printf("%zu\n", sizeof(arr));
}
int main() {
int arr[10];
printf("%zu\n", sizeof(arr)); // Line A
foo(arr); // Line B
}
Answer: Line A prints 40 (10 × 4 bytes). Line B prints 8 (pointer size on a 64-bit system). When an array is passed to a function, it decays into a pointer, sizeof inside the function returns the pointer’s size, not the array’s. This is one of the most commonly asked C tricky questions.
33. What is the output?
#include <stdio.h>
int main() {
static int x = 5;
x--;
if (x) main();
printf("%d ", x);
}
Answer: 0 0 0 0 0 , five zeros. static means x is shared across all recursive calls. When x reaches 0, the recursion stops and all 5 pending printf calls execute, each printing the current (shared) value of x, which is 0 by then.
34. What is the output?
#include <stdio.h>
#include <string.h>
int main() {
char str[] = "Hello";
printf("%zu\n", sizeof(str)); // A
printf("%zu\n", strlen(str)); // B
}
Answer: A prints 6, B prints 5. sizeof counts the null terminator \0. strlen counts only printable characters and stops at , but does not count, \0. This distinction matters whenever you allocate memory for strings.
35. What is the output?
#include <stdio.h>
int main() {
int i = 0;
for (i = 0; i < 5; i++) {
if (i == 3) continue;
printf("%d ", i);
}
}
Answer: 0 1 2 4, 3 is skipped. continue skips the rest of the current loop iteration and jumps to the increment step (i++), so the loop keeps running. This differs from break, which exits the loop entirely. A variant asking the difference between continue and break is very common in Infosys and Wipro written tests.
Looking to move beyond basic ChatGPT skills? Here’s your chance to be a part of Be part of the Bharat AI Initiative, a nationwide movement by HCL GUVI, in association with OpenAI, built to help India’s youth develop advanced ChatGPT skills absolutely free! Learn structured prompting, refine responses with clarity, and apply ChatGPT more effectively in projects, assignments, and everyday work. Learn in English, Hindi, Marathi, Tamil, or Telugu and start your free AI journey!
Common C Interview Mistakes to Avoid
- Forgetting & in scanf(), passes the value instead of the address; causes undefined behavior
- Not checking malloc() return value, if allocation fails, NULL is returned; using it crashes your program
- Forgetting free(), causes memory leaks that accumulate in long-running programs
- Using == to compare strings , compares addresses, not content; use strcmp(s1, s2) == 0 instead
- Modifying string literals , char *s = “hello”; s[0] = ‘H’; is undefined behavior; use char s[] = “hello”;
- Off-by-one in arrays , valid indices for int arr[n] are 0 to n-1; arr[n] is out of bounds
Master C programming with HCL GUVI’s C Programming Course, designed for both aspiring programmers and those preparing for C programming interviews. This course offers hands-on practice, real-world problem-solving examples, and detailed guidance on essential concepts like loops, arrays, and functions. With lifetime access, interactive learning modules, and industry-relevant projects, it’s perfect for building a solid foundation in C and excelling in technical interviews.
Conclusion
In conclusion, C interviews reward deep understanding over surface memorization. Companies want to see that you know why things work the way they do, why pointers are powerful and dangerous, why memory management is manual, and why undefined behavior exists.
Master these 35 questions, practice writing code on paper, and trace through programs mentally. That combination is what gets you hired.



Did you enjoy this article?