Skip to content
Tutorials Center
My learning

Topics

Lesson 135 of 135 ยท Practice and Review

C Interview Questions

50 common C interview questions with clear answers, from pointers, arrays and strings to malloc, structs, padding, macros, undefined behavior and threads.

C interviews test two things: whether you know how the language really behaves (what a pointer holds, where memory comes from, which code is undefined behavior, what the compiler is allowed to assume) and whether you can explain it in plain words. This page collects 50 questions that come up again and again for C, embedded and systems roles, grouped by level and topic, with short, accurate answers you can expand in your own words.

Try to answer each question out loud before you open it. If you can't explain an idea in two or three sentences, follow the link to its lesson and review it. Five questions ask you to read code and predict its output: make your prediction first, then press Run.

Tip: a short correct answer with a tiny example beats a long recital. Mention the trap ("sizeof on an array parameter gives the pointer size"), the safe habit ("I assign realloc's result to a temporary first") and the tool that catches the bug ("AddressSanitizer reports use-after-free with a stack trace"). That's what makes an answer sound like experience instead of memorization.

Junior level

Language basics

What is C, and why is it still used today?

C is a small, compiled, statically typed language from the early 1970s, designed by Dennis Ritchie to write the Unix operating system. It maps closely to what the hardware does: you work with addresses, bytes and fixed-size integers, and you manage memory yourself. There's no garbage collector and almost no runtime, so C programs start instantly and run on anything from an 8-bit microcontroller to a supercomputer. That's why operating system kernels (Linux, the core of Windows and macOS), embedded firmware, databases (SQLite, PostgreSQL), language runtimes (CPython, Lua) and many libraries are written in C, and why nearly every other language can call C functions. See Getting Started with C.

What happens when you build a C program?

Four stages. The preprocessor handles #include, #define and #if, producing one translation unit per .c file. The compiler translates each translation unit to assembly, and the assembler turns that into an object file (.o) of machine code with unresolved references to functions defined elsewhere. The linker combines the object files and libraries, connects every name to its single definition, and writes the executable. Syntax and type errors come from the compiler; "undefined reference to foo" comes from the linker. See How C Works.

What is the difference between a declaration and a definition?

A declaration tells the compiler a name and its type: int add(int a, int b); or extern int counter;. A definition also creates the thing: the function body, or the storage for a variable (int counter = 0;). You may declare something many times, but each function or global variable with external linkage must be defined exactly once in the whole program. That's why headers contain declarations and .c files contain definitions. See Declarations, Prototypes and Headers.

What is the difference between int main() and int main(void)?

Before C23, int main(void) declares a function that takes no arguments, while int main() is an old-style declaration that says nothing about the parameters, so the compiler can't check calls. C23 finally made () mean "no parameters", like in C++. Writing (void) is still the portable habit. The other standard form is int main(int argc, char *argv[]) for command-line arguments. main returns an int status to the operating system: 0 or EXIT_SUCCESS means success, and reaching the closing brace of main returns 0 automatically (since C99).

What goes in a header file, and what are include guards?

A header holds what other files need to use a module: function prototypes, type definitions (struct, typedef, enum), macros and extern declarations of global variables. It should not contain function or variable definitions (except static inline functions), or every file that includes it would define them again. Include guards (#ifndef MY_HEADER_H / #define MY_HEADER_H / #endif) or #pragma once stop a header's contents from being processed twice in one translation unit. See Multi-File Programs and Conditional Compilation.

Types and operators

How big are int, long and the other integer types?

The standard only sets minimum ranges: char is at least 8 bits, short and int at least 16, long at least 32 and long long at least 64, with sizeof(short) <= sizeof(int) <= sizeof(long) <= sizeof(long long). On today's 64-bit Linux and macOS, int is 32 bits and long is 64; on 64-bit Windows, long is still 32. When the exact width matters (file formats, protocols, hardware registers), use int32_t, uint8_t and friends from <stdint.h>. Use size_t for sizes and indexes. See Data Types and Integer Types.

What happens when an integer overflows?

Unsigned arithmetic is defined to wrap around modulo 2โฟ: UINT_MAX + 1u is 0. Signed overflow is undefined behavior: the program may produce a "wrapped" value, crash, or be optimized in surprising ways, because the compiler may assume it never happens. Check before the operation (if (a > INT_MAX - b)), use a wider type, or use C23's ckd_add/ckd_mul from <stdckdint.h>, which report overflow. See Type Limits.

What is the difference between ++i and i++?

Both add 1 to i. The value of the expression differs: ++i evaluates to the new value, i++ to the old one. So int a = 5; int b = a++; leaves b == 5, a == 6, while b = ++a would give 6 and 6. Used as a statement on its own (i++;, or in a for header), they are equivalent and compile to the same code. Modifying the same variable twice without sequencing, as in i = i++ + 1, is undefined behavior. See Assignment and Increment Operators.

Why does if (x = 5) compile, and why is it a bug?

= is assignment and == is comparison. x = 5 is an expression whose value is 5, which is "true", so the condition always succeeds and x is overwritten. GCC and Clang warn about it with -Wall ("suggest parentheses around assignment used as truth value"). Always compile with warnings on; some people write 5 == x ("Yoda conditions"), but the warning is the better fix. See if, else if and else.

What does switch fall-through mean?

A case label is only an entry point: after its statements run, execution continues into the next case unless a break (or return) stops it. That's useful when several labels share code (case 'a': case 'e': ...), and a classic bug when a break is forgotten. C23 adds the [[fallthrough]]; attribute to mark intentional fall-through so -Wimplicit-fallthrough (part of -Wextra) stays quiet. See switch Statements.

What is the difference between const and #define for constants?

#define LIMIT 100 is a preprocessor text substitution: no type, no scope, invisible to the debugger, but usable anywhere a constant expression is required (array sizes, case labels). A const int limit = 100; variable has a type and scope, but in C (unlike C++) it is not a constant expression, so it can't size a static array or be a case label. enum { LIMIT = 100 }; gives a typed int constant that works in both places, and C23's constexpr int limit = 100; gives a true typed constant. See Constants.

Strings and input

What is a string in C?

A sequence of char values ending with a null character '\0'. There is no string type: a string is stored in a char array, and functions receive a char * to its first character and walk until the terminator. strlen counts characters before '\0'; the array needs one more byte to hold it. String literals like "hello" are arrays in read-only memory, so modifying one is undefined behavior: copy it into a char name[] = "hello"; array first. See Strings.

Why was gets removed, and how do you read a line safely?

gets(buffer) has no way to know the buffer's size, so a long input line writes past the end: a buffer overflow, historically used by exploits (the 1988 Morris worm used one in fingerd). It was deprecated in C99 and removed in C11. Use fgets(buffer, sizeof buffer, stdin), which stops at the buffer size and keeps the newline (remove it with buffer[strcspn(buffer, "\n")] = '\0';). For the same reason, never use scanf("%s", ...) without a width like %19s. See Safe String Handling.

Why should you check the return value of scanf?

scanf returns the number of items it successfully stored, or EOF. If the user types abc when you asked for %d, nothing is stored, the variable keeps its old (maybe uninitialized) value, and the bad input stays in the buffer, so a loop can spin forever. Check if (scanf("%d", &n) != 1), or better, read a whole line with fgets and parse it with strtol, which reports exactly what went wrong. See Reading Input and Converting Strings and Numbers.

What does static mean in C?

It has three meanings depending on where it appears. On a local variable, it gives the variable static storage duration: it's initialized once and keeps its value between calls. On a global variable or function, it gives internal linkage: the name is private to that .c file, which is how C hides implementation details. In an array parameter, int a[static 10] promises the caller passes at least 10 elements (C99). See Scope and Storage Classes.

Code reading: integer arithmetic and characters

Predict all four values before you run it.

C Predict the output: division and chars

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Explain the output.

It prints 3 -3 1, then C 1, then 4, then 3.00. Integer division truncates toward zero, so -7 / 2 is -3, and the remainder takes the sign of the left operand, so 7 % -3 is 1. Characters are small integers: 'A' + 2 is the code of 'C'. In C a character constant like 'a' has type int, so sizeof 'a' is sizeof(int), 4 here (in C++ it would be 1). The last line converts after the integer division has already produced 3.

Mid level

Pointers and arrays

What is a pointer, and what are NULL and nullptr?

A pointer is a variable that holds the address of an object (or function). &x takes an address, *p reaches the object it points to, and the pointer's type says what's there and how big a step p + 1 is. A null pointer points to nothing; dereferencing it is undefined behavior (usually a crash). NULL is a macro for a null pointer constant (often ((void *)0) or just 0); C23 adds the nullptr keyword with its own type, nullptr_t, which can't be mistaken for an integer (for example in variadic calls or _Generic). See Pointers.

Are arrays and pointers the same thing?

No, but they're closely linked. An array is a block of elements; a pointer is a variable holding an address. In most expressions an array decays to a pointer to its first element, which is why a[i] means *(a + i) (and why i[a] also works). The exceptions show the difference: sizeof a gives the whole array's size, &a has type "pointer to array", and an array can't be assigned. A function parameter declared int a[] is really int *a, so the function can't know the length: pass it separately. See Pointers and Arrays.

What is the difference between const int *p, int *const p and const int *const p?

Read the declaration from right to left. const int *p (same as int const *p) is a pointer to const int: you can't modify the target through p, but p can point elsewhere. int *const p is a const pointer to int: the target can change, the pointer can't be reseated. const int *const p locks both. Function parameters like size_t strlen(const char *s) use the first form to promise they won't modify the caller's data. See const and Pointers.

What is a void pointer used for?

void * is a generic object pointer: any object pointer converts to it and back without a cast in C. Library functions that work on memory of any type use it: malloc returns void *, memcpy and qsort take void *. You can't dereference a void * or do arithmetic on it in standard C (GCC allows arithmetic as an extension); convert it to a concrete type (often unsigned char * for bytes) first. See void Pointers and Generic Code.

When do you need a pointer to a pointer?

When a function must change the caller's pointer, not just the data it points to: for example bool push_front(Node **head, int value) updates the list head, and strtol(text, &end, 10) stores where parsing stopped. Pointers to pointers also represent arrays of strings, like char *argv[] (which is char **argv as a parameter). See Pointers to Pointers.

What are function pointers, and where are they used?

A function pointer stores the address of a function, so code can decide at run time which function to call. The syntax is int (*compare)(const void *, const void *); a typedef makes it readable. Typical uses: comparators for qsort and bsearch, callbacks (event handlers, atexit, thrd_create), dispatch tables (an array of handlers indexed by command), and plug-in style interfaces, which is how C does polymorphism (a struct of function pointers, like a C++ vtable). See Function Pointers.

What is a dangling pointer?

A pointer that still holds the address of an object whose lifetime has ended: memory that was freed, or a local variable of a function that has returned (return &local;). Using it is undefined behavior; it may seem to work, return garbage, or corrupt other data much later. Avoid it by never returning addresses of locals (return by value, use static storage or allocate), by setting pointers to NULL after free when they stay in scope, and by having clear ownership rules. See Pointers and Functions.

Is C pass by value or pass by reference?

Always pass by value: a function receives copies of its arguments. To let a function modify a caller's variable, you pass its address, and the function writes through the pointer (void swap(int *a, int *b)). That's sometimes called "pass by reference" informally, but the pointer itself is still copied. Arrays look like an exception only because they decay to a pointer to their first element. Structs are copied in full, so large structs are usually passed as const T *. See Parameters and Return Values.

Code reading: sizeof and array parameters

Predict both numbers. The compiler warning is part of the answer.

C Predict the output: sizeof and decay

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Explain the output.

It prints in main: 40 and inside show: 8 on our 64-bit server. In main, values is an array of 10 four-byte ints. The parameter int values[10] is adjusted to int *values, so the 10 is ignored and sizeof measures a pointer. GCC even warns about it: "'sizeof' on array function parameter 'values' will return size of 'int *'". Pass the length as a separate size_t parameter.

Memory management

What is the difference between the stack and the heap?

The stack holds local variables and call frames. Allocation is automatic and very fast (moving a pointer), and the memory disappears when the function returns. It's small, typically 1โ€“8 MB per thread, so large arrays or deep recursion overflow it. The heap is memory you request with malloc/calloc/realloc and release with free. It's much larger and lives until you free it, so it can outlive the function that created it, but each allocation costs more and you're responsible for freeing it exactly once. See Memory Layout.

What is the difference between malloc, calloc and realloc?

malloc(size) returns uninitialized memory. calloc(count, size) returns memory set to all-bits-zero, and implementations return NULL if count * size would overflow. realloc(p, new_size) resizes a block, possibly moving it (copying the old contents); realloc(NULL, n) acts like malloc(n). All return NULL on failure, and every successful allocation must be passed to free exactly once. Write p = malloc(n * sizeof *p); so the size follows the pointer's type automatically. See Dynamic Memory.

What is wrong with p = realloc(p, new_size);?

If realloc fails, it returns NULL and leaves the old block allocated. Assigning the result straight back to p overwrites your only pointer to that block, so it leaks, and the code that follows will probably dereference NULL. Use a temporary: int *bigger = realloc(p, new_size); if (bigger == NULL) { /* handle, p still valid */ } else { p = bigger; }. See Building a Dynamic Array.

What are memory leaks, double frees and use-after-free, and how do you find them?

A leak is allocated memory that is never freed, usually because the last pointer to it was lost; long-running programs slowly run out of memory. A double free calls free twice on the same block, and use-after-free reads or writes through a pointer after free: both are undefined behavior that corrupts the allocator and are common security holes. Find them with AddressSanitizer (-fsanitize=address -g, which also catches buffer overflows) or Valgrind, and prevent them with clear ownership (who frees what), one cleanup path per function (goto cleanup), and setting pointers to NULL after freeing. See Memory Errors.

What are the segments of a C program in memory?

Typically: text (the machine code, read-only), read-only data (string literals and const globals), data (initialized globals and static variables), BSS (zero-initialized globals and statics, which take no space in the executable file), the heap (dynamic allocations, growing upward on most systems) and the stack (call frames, growing downward). Memory-mapped regions for shared libraries sit in between. The C standard doesn't require this layout, but every mainstream system uses something like it. See Memory Layout of a C Program.

Structures, unions and enums

What is the difference between a struct and a union?

A struct stores all its members side by side, so its size is at least the sum of the members. A union stores all its members at the same address, so it's as big as its largest member (plus padding) and holds only one member's value at a time. Unions save memory for variants and, combined with a tag field, form a tagged union: struct Value { enum Kind kind; union { int i; double d; char *s; }; };. Reading a different member than the one last written reinterprets the bytes, which C allows (unlike C++). See Unions.

Why is sizeof a struct often bigger than the sum of its members?

Because of padding. Each type has an alignment requirement (a 4-byte int usually must start at an address divisible by 4), so the compiler inserts unused bytes between members and at the end, making every element of an array of the struct correctly aligned too. Ordering members from largest to smallest alignment usually minimizes padding. offsetof shows where each member starts, and alignof/alignas (C11) inspect and control alignment. See Padding and Alignment.

What does typedef do, and when should you use it?

typedef creates an alias for an existing type: typedef unsigned long long u64;, typedef struct Point Point; (so you can write Point instead of struct Point), or typedef int (*Comparator)(const void *, const void *); to tame function pointer syntax. It doesn't create a new, distinct type. Use it for readability and for opaque handles (typedef struct Parser Parser; in a header), but avoid hiding pointers behind a typedef (typedef Node *NodePtr;), which makes const and ownership harder to see. See typedef.

What are bit-fields, and what are their limits?

Bit-fields let a struct member occupy a given number of bits: struct Flags { unsigned ready : 1; unsigned mode : 3; };. They pack small values compactly and read nicely. But the layout is largely implementation-defined: bit order, whether fields cross storage units, and the signedness of plain int fields. So don't use bit-fields to match hardware registers or file formats portably; use explicit masks and shifts on fixed-width integers instead. You also can't take the address of a bit-field. See Bit-Fields.

What are enums in C, and how do they differ from C++ enums?

An enum defines named integer constants: enum Color { RED, GREEN, BLUE }; gives 0, 1 and 2. In C the constants are plain ints in the surrounding scope, and an enum variable converts freely to and from integers, so there's no type safety. Enums are ideal for states and switch statements (GCC's -Wswitch warns about unhandled values). C23 lets you choose the underlying type: enum Small : unsigned char { A, B };. C++ adds scoped enum class, which C doesn't have. See Enumerations.

Code reading: padding

Predict both sizes and the offset of count in each struct.

C Predict the output: struct padding

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Explain the output.

On our x86-64 server it prints Loose: size 12, count at offset 4 and Tight: size 8, count at offset 0. In Loose, three padding bytes follow tag so count starts on a 4-byte boundary, and three more follow flag so the struct's size is a multiple of 4. In Tight, the two chars share the last 4-byte slot, needing only two bytes of tail padding. Exact numbers are implementation-defined, but this layout is what every mainstream 32- and 64-bit compiler produces.

The preprocessor

What are the pitfalls of function-like macros?

Macros substitute text before compilation, so they ignore precedence, types and scope. #define SQUARE(x) x * x turns SQUARE(1 + 2) into 1 + 2 * 1 + 2, which is 5. Parenthesize every parameter and the whole body: ((x) * (x)). Even then, an argument with side effects is evaluated twice: SQUARE(i++) modifies i twice without sequencing, which is undefined behavior. Multi-statement macros should be wrapped in do { ... } while (0) so they behave like one statement after an if. Prefer static inline functions, which have none of these problems. See Macros.

What is the difference between a macro and an inline function?

A macro is text substitution done by the preprocessor: no type checking, arguments may be evaluated several times, hard to debug, but it can do things functions can't (stringize with #, paste tokens with ##, take any type, use __FILE__/__LINE__ of the caller). An inline function is a real function with typed parameters, evaluated once, visible in the debugger; inline is just a hint that the compiler may expand it at the call site. In headers you normally write static inline. See inline Functions.

Code reading: a macro without parentheses

Predict both lines.

C Predict the output: macro expansion

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Explain the output.

It prints 16 and then 24. 3 * DOUBLE_BAD(4) expands to 3 * 4 + 4, and multiplication binds tighter, so the result is 12 + 4. With parentheses around the whole body, 3 * ((4) + (4)) is 24. The macro looks like a function call, but it's just text.

Senior level

Undefined behavior and the type system

What is undefined behavior, and how is it different from unspecified and implementation-defined behavior?

Undefined behavior (UB) means the standard places no requirements at all: signed overflow, out-of-bounds access, dereferencing NULL, use-after-free, data races, reading uninitialized automatic variables in many cases. The compiler may assume UB never happens and optimize on that assumption, so effects can appear far from the bug. Implementation-defined behavior must be consistent and documented by the compiler (the size of int, the result of right-shifting a negative number). Unspecified behavior allows several outcomes without documentation (the order in which function arguments are evaluated). See Undefined Behavior.

Why can the optimizer delete a check like if (x + 1 < x)?

For a signed int x, x + 1 can only be smaller than x if it overflows, and signed overflow is UB, so the compiler may assume it never happens and fold the condition to false, removing the check. Write the test so it can't overflow: if (x == INT_MAX) or if (x > INT_MAX - 1), or use ckd_add (C23). The same reasoning lets compilers remove NULL checks that come after a pointer was already dereferenced. This is why "it worked in debug mode" is not proof that code is correct.

What is the strict aliasing rule?

An object may only be accessed through an lvalue of a compatible type (ignoring qualifiers and signedness), a struct or union containing such a type, or a character type. So reading a float through an int * is UB, and the optimizer relies on this to keep values in registers. Inspecting any object as bytes through unsigned char * is always allowed. For type punning, use memcpy (compilers optimize it away) or a union, which C permits. GCC's -fno-strict-aliasing turns off the assumption, which some projects (like the Linux kernel) use.

What does restrict mean?

restrict (C99) on a pointer parameter is a promise from the programmer: for the duration of the function, the object this pointer accesses is accessed only through it (no other pointer aliases it). That lets the compiler reorder and vectorize loads and stores. memcpy is declared with restrict parameters, which is why overlapping buffers need memmove instead. Breaking the promise is undefined behavior, and the compiler can't check it for you. See Pointers and Functions.

What are integer promotions and the usual arithmetic conversions?

Before arithmetic, types smaller than int (char, short, bit-fields) are promoted to int (or unsigned int if int can't hold all their values). Then, for a binary operator, both operands are converted to a common type: if one is floating point, to that; otherwise to the larger rank, and if the same rank, signed converts to unsigned. That last rule causes the famous surprises: -1 < 1u is false because -1 becomes UINT_MAX, and strlen(s) - 1 wraps around for an empty string. See Type Conversions and Casts.

What is wrong with i = i++ or a[i] = i++?

Both modify i and also use or modify it again in the same expression without the two accesses being sequenced (C11 replaced "sequence points" with "sequenced before" rules, but the result is the same). That's undefined behavior, not just "unspecified order": different compilers really print different results. Function call arguments are also evaluated in an unspecified order, so printf("%d %d", i++, i++) is UB too. Split such code into separate statements. See Assignment and Increment Operators.

Code reading: signed and unsigned

Predict both lines. The compiler warning is a clue.

C Predict the output: signed vs unsigned

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Explain the output.

It prints -1 < 1u: false and then a + b = 300. In the comparison, int and unsigned int have the same rank, so -1 is converted to unsigned int, becoming 4294967295, which is not less than 1. GCC warns: "comparison of integer expressions of different signedness". In the addition, both unsigned char operands are first promoted to int, so the sum is 300 and doesn't wrap at 255; it would only wrap if you stored it back into an unsigned char.

Systems and portability

What does volatile mean, and is it enough for threads?

volatile tells the compiler that every read and write of the object is an observable side effect, so it must not cache the value in a register or remove "redundant" accesses. Its proper uses are memory-mapped hardware registers, variables changed in signal handlers (volatile sig_atomic_t), and locals that must survive longjmp. It is not a synchronization tool: it gives no atomicity and no ordering between threads. For shared data, use _Atomic/<stdatomic.h> or a mutex. See Multithreading.

What is a race condition, and how do you prevent it in C?

A data race happens when two threads access the same memory at the same time, at least one writes, and nothing orders the accesses. In C11 and later it's undefined behavior; in practice you lose updates (two counter++ operations reading the same old value) or see torn values. Prevent it with a mutex (pthread_mutex_lock or C11 mtx_lock) around the shared data, atomic operations (atomic_fetch_add) for simple counters and flags, or by not sharing (each thread works on its own data and results are combined after join). Also avoid non-reentrant functions like strtok and rand in threads. See Multithreading.

What is the difference between internal and external linkage?

Linkage decides whether the same name in different translation units refers to the same entity. Functions and global variables have external linkage by default: they're visible to the linker and can be used from other files through an extern declaration. Marking them static gives internal linkage, so the name is private to its file and can't clash with names elsewhere. Local variables have no linkage. Good C modules expose a small set of external functions in a header and keep everything else static. See Multi-File Programs and Linkage.

What is endianness, and how do you write portable binary data?

Endianness is the byte order of multi-byte values in memory: little-endian (x86, most ARM setups) stores the least significant byte first, big-endian stores the most significant first (and is the "network byte order" of internet protocols). Writing a struct with fwrite bakes in your machine's byte order, padding and type sizes. For portable files and protocols, choose a byte order and serialize each field explicitly with shifts: out[0] = value & 0xFF; out[1] = (value >> 8) & 0xFF; ..., which works the same on every machine. See Binary Files.

How do you write generic code in C without templates?

Three common techniques. void * plus element size and function pointers, like qsort(base, count, size, compare): flexible, but no type checking. Macros that generate type-specific code (DEFINE_VECTOR(int) expanding to struct vector_int and its functions): type-safe and fast, but harder to debug. _Generic (C11), which picks an expression by the type of its argument, for type-generic interfaces like <tgmath.h>'s sqrt that works on float, double and long double. C23's typeof also helps write safer macros. See void Pointers and Generic Code and Macros.

Modern C and professional practice

What did C99, C11 and C23 add?

C99: // comments, declarations anywhere and in for headers, <stdint.h>, <stdbool.h>, long long, inline, designated initializers, compound literals, variable-length arrays, restrict, snprintf. C11: threads (<threads.h>), atomics, _Generic, _Static_assert, alignment control, anonymous structs and unions, and the removal of gets. C23: bool/true/false, nullptr, constexpr, typeof, auto type inference, [[attributes]], digit separators (1'000'000), binary literals, #embed, <stdckdint.h> checked arithmetic, <stdbit.h>, and () meaning no parameters. C17 was a bug-fix release. See Modern C: C99 to C23.

How do you make C code safer in practice?

Compile with warnings (-Wall -Wextra, often -Werror in CI), run tests under AddressSanitizer and UndefinedBehaviorSanitizer (-fsanitize=address,undefined), and use static analyzers. In the code: check every return value (malloc, fopen, scanf, fclose), use bounded functions (snprintf, fgets, strtol with error checks), pass buffer sizes with every buffer, document who owns and frees each allocation, use const wherever data shouldn't change, keep functions small with a single cleanup path, and avoid UB-prone tricks. See Best Practices and Common Mistakes and Debugging C Programs.

How would you debug a program that crashes with a segmentation fault?

Reproduce it with a debug build (-g -O0). Run it under gdb, and when it stops, bt shows the call stack and print shows the variables, which usually reveals a NULL or garbage pointer. If the crash is a symptom of earlier memory corruption, rebuild with -fsanitize=address, which stops at the first invalid access with a precise report, or run Valgrind. Then check the usual suspects: an unchecked malloc or fopen, an off-by-one loop, a missing '\0', a dangling pointer, or a stack overflow from deep recursion. See Debugging C Programs.

How does C differ from C++?

C is the smaller language: no classes, references, templates, exceptions, namespaces, function overloading or standard containers, so you build these ideas from structs, function pointers and macros, and manage resources by hand instead of with destructors (RAII). Most C is valid C++, but not all: C converts void * to other pointers implicitly, allows int *p = malloc(...) without a cast, has designated initializers in any order, VLAs and restrict, and sizeof 'a' is sizeof(int). The two languages share many recent features (nullptr, constexpr, attributes, auto), with different details. See C and C++.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. A function is declared void f(int a[10]) and prints sizeof a. What does it print on a typical 64-bit system?

    An array parameter is adjusted to a pointer, so sizeof gives the pointer's size. GCC warns about exactly this.
  2. 2. Which statement about signed integer overflow is correct?

    Only unsigned arithmetic is defined to wrap. Signed overflow is UB, and optimizers rely on that, for example to delete overflow checks written after the fact.
  3. 3. What is volatile NOT suitable for?

    volatile prevents the compiler from caching or removing accesses, but gives no atomicity or ordering between threads. Use atomics or mutexes for that.
  4. 4. What does -1 < 1u evaluate to?

    With operands of the same rank, the signed one converts to unsigned, so the comparison is UINT_MAX < 1, which is false (0).
  5. 5. Why should a header file not contain the definition of a global variable like int counter = 0;?

    Each including translation unit gets its own definition. Put extern int counter; in the header and the single definition in one .c file.

Summary

  • Junior questions check the foundations: the build stages, declarations vs definitions, main, headers and include guards, integer sizes and overflow, ++, = vs ==, strings and the null terminator, safe input, and the meanings of static and const.
  • Mid-level questions focus on pointers and memory: decay and sizeof, const with pointers, void *, pointers to pointers, function pointers, dangling pointers, stack vs heap, the allocation functions, realloc safety and memory error tools.
  • Struct questions cover unions, padding and alignment, typedef, bit-fields and enums; preprocessor questions cover macro pitfalls and inline functions.
  • Senior questions dig into undefined behavior and what optimizers do with it, strict aliasing, restrict, conversions, volatile vs atomics, races, linkage, endianness, generic code, the C standards and professional tooling.
  • In every answer, a precise explanation, a tiny example, the trap and the tool that catches it are what interviewers reward.

You've reached the end of the C course. Keep practicing with the exercises and the 50 classic programs, keep the cheat sheet close, and come back to the C course overview whenever you want to review a topic. Happy coding!