Why this matters
You learn C because it explains the rest of programming. Python, JavaScript, and even the operating system you are using were all built with C somewhere in their stack. When you write C, you meet pointers, memory addresses, and the call stack directly instead of through a layer of abstractions. That knowledge transfers everywhere, because debugging a mysterious crash in a modern language usually comes down to the same memory rules that C puts right in front of you.
C is also tiny. The language itself has only a few dozen keywords, so there is surprisingly little syntax to memorize. What makes C difficult is not the grammar but the honesty. The compiler does almost nothing to protect you. There is no garbage collector, no bounds checking, and no safety net. You allocate memory, you release it, and you live with the consequences of your choices.
That honesty is exactly why C still matters decades after it was created. It produces small, fast programs that run on everything from tiny microcontrollers to the largest supercomputers. If you want to write an operating system kernel, a device driver, or firmware for an embedded chip, C is often the default choice. Learning it makes you a more careful and more capable programmer in every other language you touch.
The big picture
Think of C as a thin, transparent layer stretched over the machine. When you declare a variable, you are really reserving a few bytes of memory and giving them a name. When you declare a pointer, you are storing an address. When you call a function, the processor jumps to a block of code and then returns. Almost nothing hidden happens between your source code and the hardware.
A C program is mostly a collection of functions. Execution begins in a function called main, and from there functions call other functions. There is no runtime system quietly managing things for you: no virtual machine, no automatic memory reclamation, and no objects with secret behavior. You decide where each piece of data lives and how long it survives, and the language trusts you to get it right.
Memory in a running C program is divided into a few regions. Local variables live on the call stack, which grows and shrinks as functions are entered and left. Dynamically allocated memory lives on the heap and stays until you explicitly release it. Global and static variables live in fixed storage for the entire lifetime of the program. Much of learning C is learning which region to reach for, and why.
Core ideas
Declaration vs definition
A function definition is the real thing: a name, a parameter list, and a body full of statements that actually run. A declaration, usually called a prototype, only tells the compiler the function name, its return type, and the types of its parameters. The compiler needs that information before it reaches a call, because C checks each call as it reads your file from top to bottom.
Because of this top-to-bottom rule, you must either define a function before you call it or place a prototype near the top of the file. A prototype ends with a semicolon, while a definition ends with a body in braces. Header files are mostly collections of prototypes, which is how one source file can safely call functions that are defined in a completely different source file.
int square(int x);
int square(int x) {
return x * x;
}
Watch out. Forgetting the prototype and defining the function later. The compiler then guesses an old-style signature and you get confusing type errors. Put a prototype above every caller, or simply move the whole definition up.
Parameters passed by value
In C, every argument is copied into its parameter. When you call a function with a variable, the function receives a brand-new copy of that value. Changing the parameter changes only the copy, and the original variable back in the caller stays exactly as it was. This is called pass by value, and it is the only kind of parameter passing that C actually has.
This is reassuring because a function cannot accidentally corrupt your variables. It is also limiting, because a copy is useless if you want the function to change something in the caller. To get that effect you pass a pointer instead. The pointer itself is still copied, but the address it holds continues to point at the original data, so writing through it changes the real object.
void bump(int n) {
n = n + 1;
}
int main(void) {
int x = 5;
bump(x);
return 0;
}
Watch out. Expecting bump(x) to change x. It cannot, because n is only a copy. To truly change x, pass &x and declare the function as void bump(int *n) with the body *n = *n + 1.
Pointers as parameters
A pointer parameter lets a function reach across the frame boundary into the caller's memory. Instead of copying a value, you copy an address. The function dereferences that address to read or write the original variable. This is how C simulates pass by reference, even though, strictly speaking, the pointer itself is still passed by value like everything else.
Pointers also avoid expensive copies of large data. Passing a big struct by value copies every single byte; passing a pointer copies just one address. When the function is only supposed to read the data, mark the pointer const, as in const int *p, which is a promise that the function will not modify anything through that pointer.
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
Watch out. Passing values instead of addresses, as in swap(x, y), which does nothing at all. Call swap(&x, &y) instead. Also remember to dereference with the star inside the function, because assigning to a alone only changes the local pointer.
Returning values and pointers
A function hands a value back with the return keyword, and that value must match the declared return type. For small values this is cheap and natural. You can also return a pointer, which is useful for handing back a reference to a large object or to a block of memory you allocated. Returning a pointer means you give back an address rather than a copy of the data.
The dangerous case is returning a pointer to a local variable. A local dies when its function returns, so the pointer would refer to memory that no longer belongs to you, and reading it is undefined behavior. If a pointer must outlive the call, allocate the storage on the heap with malloc, or return a pointer that the caller supplied in the first place.
#include <stdlib.h>
int *make_heap_int(int value) {
int *p = malloc(sizeof(int));
if (p != NULL) *p = value;
return p;
}
Watch out. Never return the address of a local, such as int *p = &local; return p;. That stack frame is gone. Use malloc for memory that must survive, and remember that the caller now owns the job of calling free.
The stack and stack frames
Every time you call a function, the computer pushes a stack frame onto the call stack. That frame holds the function parameters, its local variables, a few saved registers, and a return address: the exact spot in the code where execution should resume when the function finishes. When the function returns, its frame is popped off and all that local storage is immediately considered free.
This is why recursion works and why local variables vanish when a function ends. The stack is a fixed-size region, so extremely deep recursion or very large local arrays can exhaust it and cause a stack overflow. The stack grows and shrinks automatically as calls come and go, but it cannot grow forever, and you cannot safely use a frame after it has been popped.
Watch out. Assuming locals keep their values between calls. Once the frame is gone, that storage may be reused by the next call. If you need a value to persist, use a static local, a global, or heap memory.
static functions and linkage
By default a function name has external linkage, which means it is visible to the other files that make up your program. Putting the static keyword in front of a function gives it internal linkage: the function is visible only inside the single file where it is defined. This is a clean way to hide helper functions and avoid name collisions between different files.
The static keyword is overloaded in C, so its meaning depends on context. On a function it controls visibility. On a local variable it changes storage duration, making the variable live for the whole program instead of inside a stack frame. On a global variable it limits visibility. The common thread is that static means private to this file, or persistent, depending on where you write it.
static int helper(int x) {
return x + 1;
}
int public_fn(int x) {
return helper(x) * 2;
}
Watch out. Thinking a static function is shared globally. It is the opposite: it is private to one file. Two different files can each define a static helper with the same name without any conflict, because neither can see the other.
Recursion
A recursive function is one that calls itself. Each call receives a fresh stack frame with its own parameters and local variables, so the different calls do not interfere with one another. You always need a base case that stops the recursion, otherwise the calls continue forever until the stack runs out. Recursion shines for problems that are naturally defined in terms of smaller versions of themselves.
Recursion is elegant, but it costs a full stack frame for every call, so a plain loop is usually faster and safer for simple repetition. C does not guarantee tail-call optimization, so even a self-call at the very end of a function can consume a frame. Reach for recursion when the structure of the problem is genuinely tree-like or nested, not merely to avoid writing a loop.
int factorial(int n) {
if (n <= 1) return 1;
return n * factorial(n - 1);
}
Watch out. Forgetting a reachable base case causes infinite recursion and a crash. Make sure each recursive step moves closer to the base case, and that the base case returns directly without calling the function again.
Variadic functions
A variadic function accepts a variable number of arguments. You write it with a fixed set of parameters followed by an ellipsis, then use the macros from stdarg.h, named va_start, va_arg, and va_end, to walk through the extra arguments. The familiar printf function is the best-known example. Because C does not know the types of those extra arguments, you have to encode that information yourself.
This is powerful but fragile. You need some way to know how many arguments were passed and what type each one is, often through a format string or an explicit count. Reading past the real arguments, or reading them as the wrong type, is undefined behavior. Use variadic functions for genuinely flexible interfaces, and prefer ordinary typed parameters whenever you can.
#include <stdarg.h>
int sum(int count, ...) {
va_list args;
va_start(args, count);
int total = 0;
for (int i = 0; i < count; i++)
total += va_arg(args, int);
va_end(args);
return total;
}
Watch out. Calling va_arg too many times, or with a type that does not match what was passed, reads garbage or crashes. Always pass a count or a sentinel, and read exactly the types you know are there.
Function pointers
Functions live in memory too, so you can store the address of a function in a pointer and call through it. A function pointer type includes both the return type and the parameter types, which is why the syntax has a reputation for being awkward. Function pointers let you pass behavior around as data: sort with a custom comparison, register a callback, or build a table of operations you can select at runtime.
You can tame the syntax with a typedef. A pointer to a function that takes two ints and returns an int is written int (*f)(int, int). The parentheses around the star are essential, because without them you would be declaring a function that returns a pointer instead. Once it is declared, you call a function pointer just like an ordinary function, for example f(3, 4).
typedef int (*op_fn)(int, int);
int add(int a, int b) { return a + b; }
int apply(op_fn fn, int x, int y) {
return fn(x, y);
}
Watch out. Mixing up int *f(int, int), which is a function returning a pointer, with int (*f)(int, int), which is a pointer to a function. Those parentheses around the star change the meaning completely.
Functions
Functions are the unit of behavior in C. They package a sequence of statements under a useful name, hide the small details of how something is done, and let you assemble a large program out of small, testable pieces. Almost everything interesting in C happens through a function call, so understanding the calling machinery in detail pays off immediately in every program you write.
This deep dive pulls the threads together. You will see how the compiler views a declaration, exactly what gets copied when you pass an argument, how pointers let a function reach outside its own frame, and what physically happens on the stack during a call. Once this picture clicks, pointers and recursion stop feeling magical and start feeling thoroughly mechanical.
Declaration vs definition
A definition supplies a body and causes the compiler to emit the actual machine code for the function. A declaration only announces the signature so the compiler can recognize calls. The signature includes the name, the return type, and the ordered list of parameter types, but never the parameter names, which are optional in a prototype.
C processes a translation unit from top to bottom, so every function you call must already have been declared at that point. You satisfy the rule by ordering definitions so that helpers come before their callers, or by placing prototypes near the top. Header files exist largely to share those prototypes across multiple source files.
int area(int w, int h);
int area(int w, int h) {
return w * h;
}
The call stack in action
Each call pushes a frame that contains the parameters, the local variables, saved registers, and a return address telling the processor where to pick up again in the caller. When the function finishes, the frame is popped and all of its locals are forgotten. This is a real, finite block of memory, not an abstract idea.
Because frames are stacked, recursion works naturally: every invocation has its own private storage. The price is that the stack has a fixed size. Deep recursion, or a huge array allocated as a local, can exhaust it and crash the program with a stack overflow. Nothing grows the stack automatically for you.
int twice(int x) { return x + x; }
int four_times(int x) {
return twice(twice(x));
}
Pass by value
Arguments are evaluated and then copied into the parameters. The function works only with those copies, so it cannot change the variables in the caller. That makes functions predictable and keeps accidental side effects to a minimum. Pass by value is the only argument mechanism C provides.
When you do want a function to change caller state, you pass a pointer. The pointer value is copied, but the address it carries still refers to the original object, so dereferencing it reaches across the frame boundary. This is the standard C trick for producing more than one result from a function.
void set_zero(int *p) {
*p = 0;
}
Return values
The return statement produces a value whose type must match the declared return type. Returning a small integer or floating-point value is very cheap because it travels in a register. Returning a large struct can involve copying all of its bytes, although compilers optimize this heavily when they can.
You may return a pointer instead of the data itself. That is perfectly fine when the pointer refers to storage that outlives the call, such as a heap allocation, a global, or a buffer the caller passed in. It is a serious bug when the pointer refers to a local variable whose frame disappears the moment the function returns.
int square(int x) {
return x * x;
}
Pointers as output parameters
A very common C idiom is to use the return value for status and pointer parameters for the actual results. A parsing function might return 1 on success and write the parsed number through an int pointer. This keeps error handling explicit, because the caller is encouraged to check the status before trusting the output variable.
The technique works because the pointer gives the function write access to memory that the caller owns. The caller declares an ordinary local, passes its address, and afterwards finds the result waiting there. It is the closest C gets to returning several values at once.
int divide(int a, int b, int *out) {
if (b == 0) return 0;
*out = a / b;
return 1;
}
Scope and linkage
Local variables are scoped to the block where they are declared and live inside the current frame. They are created on entry and destroyed on exit. Global variables and variables declared static live for the whole run of the program, and they are zero-initialized automatically if you do not give them a value.
Function names normally have external linkage, so the linker can connect calls in one file to definitions in another. Marking a function static gives it internal linkage and hides it from other files. Choosing the right storage duration and visibility is a major part of designing a clean C program.
static int helper(int x) {
return x + 1;
}
Recursion and frames
A recursive call builds another frame on top of the current one, complete with its own copies of the parameters and locals. That isolation is what makes problems like factorial, tree traversal, and divide-and-conquer sorting so natural to express recursively. Each level works with its own smaller piece of the problem.
You must include a base case that returns without recursing, otherwise the frames pile up until the stack overflows. Also remember that C makes no tail-call optimization promise, so even a call in return position consumes a fresh frame. For a straightforward loop, iteration is the safer tool.
int fib(int n) {
if (n < 2) return n;
return fib(n - 1) + fib(n - 2);
}
Function pointers as callbacks
A function pointer stores the address of executable code, letting you decide which function to call at runtime. The standard library function qsort takes a comparator function pointer, which is precisely how one sorting routine can handle any kind of data you throw at it. You provide the comparison logic and qsort provides the algorithm.
Use a typedef to keep the declaration readable, then pass functions around just like values. Callbacks appear throughout C programming, from signal handlers to event loops and plugin systems, because they let a library call back into your code without knowing anything about your application.
int inc(int x) { return x + 1; }
int call(int (*f)(int), int v) {
return f(v);
}
Function reference
These are the functions you will reach for most often. Each one is shown with its syntax, its inputs and outputs, a working example, and the mistakes to avoid.
function definition
User-defined form
A function definition is where you actually write a function: a return type, a name, a parameter list, and the body that runs when it is called. This is the real implementation, not just a declaration.
| Syntax | int add(int a, int b) { return a + b; } |
|---|---|
| Parameters | a — The first integer operand b — The second integer operand |
| Returns | Whatever the return statement produces; here the sum of a and b. A void function returns no value. |
int add(int a, int b) {
return a + b;
}
int main(void) {
printf("%d\n", add(2, 3));
return 0;
}
What you can do with it. Package a repeated calculation into one reusable block Split a large program into small, testable pieces Hide implementation detail behind a clear name
Choose it when. Choose a definition when you are implementing real behavior, rather than a prototype that only announces the interface to the compiler.
| Mistake | Fix |
|---|---|
| Forgetting to return a value from a non-void function | End every path with a return of the correct type, or the caller reads garbage. |
| Returning a value whose type differs from the declared return type | Make the returned expression match the signature, or cast it deliberately. |
function prototype
Declaration
A prototype tells the compiler a function's name, return type, and parameter types before the definition appears. C reads your file top to bottom, so any call needs this information ahead of it.
| Syntax | int add(int a, int b); |
|---|---|
| Parameters | a — The first parameter's type and name b — The second parameter's type and name |
| Returns | Nothing at runtime; a prototype is purely compile-time information. |
int add(int a, int b);
int main(void) {
add(2, 3);
return 0;
}
int add(int a, int b) {
return a + b;
}
What you can do with it. Call a function defined later in the same file Share interfaces across files through a header Hide an implementation while exposing its API
Choose it when. Choose a prototype when the definition lives later or in another file, rather than simply moving the whole definition above the first call.
| Mistake | Fix |
|---|---|
| Omitting the trailing semicolon | A prototype is a statement, so it ends with ; while a definition ends with a body in braces. |
| Prototype and definition with different types | Keep them identical; a mismatch is a compile error that signals an inconsistent interface. |
pointer parameter
Parameter form
A pointer parameter passes an address instead of a copy, so the function can read or change the caller's actual variable. It also avoids copying large blocks of data.
| Syntax | void increment(int *p) { (*p)++; } |
|---|---|
| Parameters | p — Address of the integer to modify |
| Returns | Nothing; the effect happens through the pointed-to address. |
void increment(int *p) {
(*p)++;
}
int main(void) {
int x = 5;
increment(&x);
return 0;
}
What you can do with it. Swap two caller variables Let a function report several results through out-parameters Avoid copying a large struct on every call
Choose it when. Choose a pointer parameter when the function must modify caller data or skip an expensive copy, rather than plain pass by value.
| Mistake | Fix |
|---|---|
| Passing a value instead of an address, as in increment(x) | Pass &x so the parameter holds the address of the real variable. |
| Assigning to the pointer instead of dereferencing it | Write (*p)++ to change the pointee; p++ only moves the local pointer. |
function pointer
Pointer type
A function pointer stores the address of a function, letting you pass behavior around as data or choose a function at runtime. This is how C implements callbacks and dispatch tables.
| Syntax | int (*op)(int, int) = &add; |
|---|---|
| Parameters | op — Pointer to a function taking two ints and returning int |
| Returns | Calling through the pointer returns whatever the pointed-to function returns. |
#include <stdio.h>
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int main(void) {
int (*op)(int, int) = add;
printf("%d\n", op(7, 2));
op = sub;
printf("%d\n", op(7, 2));
return 0;
}
What you can do with it. Pass a callback into a sorting or event routine Build a table of handlers selected by an index Implement a simple strategy pattern in C
Choose it when. Choose a function pointer when behavior must be pluggable at runtime, rather than a direct call to one fixed function.
| Mistake | Fix |
|---|---|
| Mixing up int *f(void) with int (*f)(void) | Parenthesize the star: int (*f)(void) is a pointer to a function. |
| Calling a function pointer that is NULL | Check for NULL before calling, since calling a null address crashes. |
printf
Standard library function
printf writes formatted text to standard output. It reads a format string and swaps each placeholder, such as %d, for the value you supply.
| Syntax | int printf(const char *format, ...); |
|---|---|
| Parameters | format — Text with conversion specifiers like %d and %s ... — Values matching those specifiers |
| Returns | The number of characters written, or a negative value on an output error. |
#include <stdio.h>
int main(void) {
int n = 42;
printf("The answer is %d\n", n);
printf("%s scored %.1f\n", "Ana", 9.5);
return 0;
}
What you can do with it. Print debug values while developing Format numbers, strings, and tables for the console Build aligned reports with width specifiers
Choose it when. Choose printf when you need formatted output with placeholders, rather than puts for a plain line of text.
| Mistake | Fix |
|---|---|
| Using a specifier that does not match the argument type | Pair %d with int, %ld with long, %s with char *, and so on; a mismatch is undefined behavior. |
| Leaving a placeholder with no matching argument | Supply one argument per specifier, in order, or printf reads nonexistent values. |
scanf
Standard library function
scanf reads formatted input from standard input and stores the converted values at the addresses you pass. It is the input counterpart to printf.
| Syntax | int scanf(const char *format, ...); |
|---|---|
| Parameters | format — Specifiers describing the expected input ... — Pointers to where converted values are stored |
| Returns | The number of items successfully assigned, or EOF if input ends first. |
#include <stdio.h>
int main(void) {
int age;
printf("Age? ");
if (scanf("%d", &age) == 1)
printf("You are %d\n", age);
return 0;
}
What you can do with it. Read a number typed by the user Parse simple whitespace-separated fields Check whether input matched the expected form
Choose it when. Choose scanf for quick, simple parsing, rather than fgets when you need robust line-oriented input and whitespace control.
| Mistake | Fix |
|---|---|
| Forgetting the & before the destination variable | scanf needs an address, so write &age; passing age writes to a random location. |
| Using a bare %s into a fixed buffer | Use a width like %19s to bound the write and prevent a buffer overflow. |
malloc
Standard library function
malloc allocates a block of heap memory of a requested size and returns a pointer to it. The bytes are uninitialized, so you must set them before reading.
| Syntax | void *malloc(size_t size); |
|---|---|
| Parameters | size — Number of bytes to allocate |
| Returns | A pointer to the block, or NULL when allocation fails. |
#include <stdlib.h>
int main(void) {
int *a = malloc(5 * sizeof *a);
if (a == NULL) return 1;
for (int i = 0; i < 5; i++) a[i] = i;
free(a);
return 0;
}
What you can do with it. Create arrays whose size is known only at runtime Build linked lists, trees, and other dynamic structures Allocate large objects that would overflow the stack
Choose it when. Choose malloc for memory that must outlive the current function call, rather than a stack local that vanishes on return.
| Mistake | Fix |
|---|---|
| Not checking the result for NULL | Always test the pointer before use, because allocation can fail. |
| Computing the size in elements rather than bytes | Use count * sizeof *ptr so the byte count is correct for the type. |
free
Standard library function
free returns a block previously obtained from malloc, calloc, or realloc to the allocator. After you free a pointer, using it is undefined behavior.
| Syntax | void free(void *ptr); |
|---|---|
| Parameters | ptr — A pointer from malloc, or NULL |
| Returns | Nothing. |
#include <stdlib.h>
int main(void) {
char *buf = malloc(100);
if (!buf) return 1;
/* use buf here */
free(buf);
buf = NULL;
return 0;
}
What you can do with it. Release a dynamic array when you are done Destroy nodes as you unlink them Pair every allocation with cleanup to avoid leaks
Choose it when. Choose free whenever you finish with heap memory, rather than letting the allocation leak until the program ends.
| Mistake | Fix |
|---|---|
| Freeing the same pointer twice | Set the pointer to NULL after freeing, and free each allocation exactly once. |
| Using memory after it was freed | Treat the pointer as dead after free; do not read or write through it. |
strlen
Standard library function
strlen returns how many characters are in a C string, not counting the terminating null byte. It walks the memory until it finds that '\0'.
| Syntax | size_t strlen(const char *s); |
|---|---|
| Parameters | s — A null-terminated string |
| Returns | The length in bytes, excluding the trailing '\0'. |
#include <stdio.h>
#include <string.h>
int main(void) {
char s[] = "hello";
size_t n = strlen(s);
printf("%zu\n", n);
return 0;
}
What you can do with it. Size a buffer before copying Set loop bounds when scanning characters Validate that input meets a length limit
Choose it when. Choose strlen for the length of a proper C string, rather than sizeof, which counts the storage of the array instead.
| Mistake | Fix |
|---|---|
| Calling strlen on a buffer that is not null-terminated | Ensure a '\0' terminator exists, or strlen reads past the buffer. |
| Allocating exactly strlen(s) bytes for a copy | Add one byte for the terminator, so allocate strlen(s) + 1. |
strcpy
Standard library function
strcpy copies a string, including its null terminator, into a destination buffer. It does no bounds checking at all, so the destination must already be big enough.
| Syntax | char *strcpy(char *dest, const char *src); |
|---|---|
| Parameters | dest — Destination buffer with enough space src — Null-terminated source string |
| Returns | The destination pointer dest. |
#include <stdio.h>
#include <string.h>
int main(void) {
char dest[20];
strcpy(dest, "hello");
puts(dest);
return 0;
}
What you can do with it. Copy a known-short string into a prepared buffer Initialize a character array from a literal Duplicate text into storage you own
Choose it when. Choose strcpy only when the destination is provably large enough, rather than snprintf when the source length is untrusted.
| Mistake | Fix |
|---|---|
| Copying into a destination smaller than the source | Guarantee the space, or use snprintf to cap the write. |
| Copying overlapping regions | Overlap is undefined; use memmove for raw bytes or avoid overlapping strings. |
qsort
Standard library function
qsort sorts an array in place using a comparator function you write. It works on raw bytes, so it can sort any element type, not just integers.
| Syntax | void qsort(void *base, size_t n, size_t size, int (*cmp)(const void *, const void *)); |
|---|---|
| Parameters | base — Pointer to the first element n — Number of elements size — Size of one element in bytes cmp — Comparator returning negative, zero, or positive |
| Returns | Nothing; the array is reordered in place. |
#include <stdlib.h>
int cmp_int(const void *a, const void *b) {
int x = *(const int *)a, y = *(const int *)b;
return (x > y) - (x < y);
}
int main(void) {
int v[] = {3, 1, 4, 1, 5};
qsort(v, 5, sizeof v[0], cmp_int);
return 0;
}
What you can do with it. Sort an array of integers or structs Apply a custom order such as descending Sort string pointers with strcmp in the comparator
Choose it when. Choose qsort for a generic in-place sort in C, rather than writing your own sorting loop.
| Mistake | Fix |
|---|---|
| Subtracting two values to compare them | Subtraction can overflow; compare with > and < and return -1, 0, or 1. |
| Passing the array's total byte size as size | Pass sizeof one element, and pass the element count separately. |
memcpy
Standard library function
memcpy copies a fixed number of bytes from one region of memory to another. It is fast and type-agnostic, but the source and destination must not overlap.
| Syntax | void *memcpy(void *dest, const void *src, size_t n); |
|---|---|
| Parameters | dest — Destination memory block src — Source memory block n — Number of bytes to copy |
| Returns | The destination pointer dest. |
#include <string.h>
int main(void) {
int src[3] = {1, 2, 3};
int dst[3];
memcpy(dst, src, sizeof src);
return 0;
}
What you can do with it. Duplicate a raw data buffer Copy a struct's bytes into a file or socket buffer Initialize an array from another array
Choose it when. Choose memcpy for a non-overlapping raw byte copy, rather than memmove when the two ranges might overlap.
| Mistake | Fix |
|---|---|
| Copying overlapping regions | Use memmove when the ranges overlap; memcpy's behavior is undefined there. |
| Passing an element count instead of a byte count | Use sizeof on the source to compute the correct number of bytes. |
puts
Standard library function
puts writes a string followed by a newline to standard output. It is the simplest choice when you have no formatting to do.
| Syntax | int puts(const char *s); |
|---|---|
| Parameters | s — The null-terminated string to print |
| Returns | A nonnegative value on success, or EOF on error. |
#include <stdio.h>
int main(void) {
puts("Hello, world!");
return 0;
}
What you can do with it. Print a single line of text Show a quick status or prompt Replace printf when there are no placeholders
Choose it when. Choose puts for a plain line of text, rather than printf when you need to format values into the output.
| Mistake | Fix |
|---|---|
| Adding your own \n and printing two newlines | puts already appends a newline, so leave it out of the string. |
| Passing something that is not a null-terminated string | Only pass proper C strings, or puts reads past the end. |
strcmp
Standard library function
strcmp compares two strings character by character and reports their lexicographic ordering. It is how you compare string contents in C.
| Syntax | int strcmp(const char *a, const char *b); |
|---|---|
| Parameters | a — First null-terminated string b — Second null-terminated string |
| Returns | Zero if equal, a negative value if a sorts before b, and a positive value if a sorts after b. |
#include <stdio.h>
#include <string.h>
int main(void) {
char a[] = "cat";
if (strcmp(a, "cat") == 0)
puts("same");
return 0;
}
What you can do with it. Test whether two strings are equal Provide a comparator to qsort for strings Order names alphabetically
Choose it when. Choose strcmp to compare the contents of strings, rather than == which only compares where they are stored.
| Mistake | Fix |
|---|---|
| Comparing strings with == | == compares pointer addresses; use strcmp to compare the characters themselves. |
| Writing if (strcmp(a, b)) when you mean equal | strcmp returns zero for equality, so test == 0 explicitly. |
Common mistakes here
| Mistake | Fix |
|---|---|
| Calling a function before any declaration is visible | Add a prototype above the caller or move the definition earlier in the file. |
| Expecting a by-value parameter to modify the caller's variable | Pass the address with & and dereference the pointer inside the function. |
| Returning a pointer to a local stack variable | Allocate the result on the heap or return a pointer the caller supplied. |
| Forgetting the base case in a recursive function | Ensure every recursive step moves toward a base case that returns directly. |
| Using va_arg without knowing the argument's real type | Pass an explicit count or format, and read exactly the types that were provided. |
The example, line by line
Here is a small but complete C program that defines a helper function and calls it from main.
| Code | What it does |
|---|---|
1#include <stdio.h> | Pulls in the standard I/O header so printf is declared before we use it. |
2int add(int a, int b) { | Defines a function named add that takes two int parameters and returns an int. |
3 return a + b; | Returns the sum; this final expression is the value the caller receives. |
4} | The closing brace ends the body of add. |
5int main(void) { | Defines main, the entry point, with void stating it takes no arguments. |
6 int sum = add(3, 4); | Calls add with 3 and 4, then stores the returned 7 in a local variable. |
7 printf("Sum: %d\n", sum); | Prints the result, using percent d as a placeholder for the integer. |
8 return 0; | Returns 0 to the operating system to signal that the program succeeded. |
9} | The closing brace ends main and therefore ends the program. |
#include <stdio.h>
int add(int a, int b) {
return a + b;
}
int main(void) {
int sum = add(3, 4);
printf("Sum: %d\n", sum);
return 0;
}
Worked variations
Swapping two variables
This variation puts pointer parameters to work. Because a and b hold addresses, writing through them changes the two variables in main rather than local copies. Pass the addresses with the ampersand operator, and the swap becomes visible to the caller.
#include <stdio.h>
void swap(int *a, int *b) {
int t = *a;
*a = *b;
*b = t;
}
int main(void) {
int x = 1, y = 2;
swap(&x, &y);
printf("%d %d\n", x, y);
return 0;
}
Choosing behavior with a callback
A function pointer lets one piece of code select another at runtime. Here apply does not know which operation it will perform; the caller passes that decision in as a pointer to a function. This is the same idea that makes library sorting routines flexible.
typedef int (*op_fn)(int, int);
int add(int a, int b) { return a + b; }
int sub(int a, int b) { return a - b; }
int apply(op_fn fn, int x, int y) {
return fn(x, y);
}
A small variadic helper
This function adds together as many integers as you give it. The count parameter tells the function how many extra arguments to read, which is essential because variadic arguments carry no type information. Always match the count and the type exactly.
#include <stdarg.h>
int total(int count, ...) {
va_list ap;
va_start(ap, count);
int sum = 0;
while (count--) sum += va_arg(ap, int);
va_end(ap);
return sum;
}
Common mistakes
| Mistake | Fix |
|---|---|
| Confusing the assignment operator = with the comparison operator == | Use == to compare values and = to assign, and compile with warnings enabled. |
| Writing past the end of an array | C performs no bounds checking, so track the length yourself and verify every index. |
| Forgetting to free memory obtained from malloc | Pair every successful malloc with exactly one free when you are done with the memory. |
| Dereferencing an uninitialized pointer | Initialize pointers to NULL and check them before you read or write through them. |
| Declaring a huge local array and overflowing the stack | Allocate large buffers on the heap or make them static instead of automatic. |
Practice
- Write a function is_even(int n) that returns 1 for even numbers and 0 for odd ones.
- Write swap_int(int *a, int *b) and prove it works by calling it from main.
- Write a recursive function that returns the sum of all integers from 1 up to n.
- Write a variadic function max_int(int count, ...) that returns the largest argument.
- Build a small table of function pointers for add, subtract, and multiply, then call each one.