C Language Cheatsheet
A complete C programming language cheatsheet covering basics to advanced topics — data types, pointers, memory management, structures, preprocessor, file I/O, and common pitfalls.
C is a general-purpose, procedural systems programming language that provides low-level memory access and maps efficiently to machine instructions. It is the foundation of operating systems, embedded systems, and many other languages.
This cheatsheet goes from beginner fundamentals to intermediate and advanced topics.
# Compile a single filegcc hello.c -o hello
# Compile with warnings and standardsgcc -Wall -Wextra -std=c17 -O2 hello.c -o hello
# Multi-file projectgcc -c file1.c # produces file1.ogcc -c file2.cgcc file1.o file2.o -o program
# Link math librarygcc main.c -lm -o main
# Debug buildgcc -g -O0 main.c -o mainCommon flags:
-Wall -Wextra— enable useful warnings-std=c11/-std=c17/-std=c23— language standard-O0to-O3/-Os— optimization levels-g— debug symbols-Iinclude path,-Llibrary path,-llink library
#include <stdio.h>
int main(void) { printf("Hello, C!\n"); return 0;}mainreturnsint(0 = success).- Prefer
int main(void)overint main()for clarity.
| Type | Size (bytes) | Range (approx) |
|---|---|---|
char |
1 | -128 to 127 or 0 to 255 |
signed char |
1 | -128 to 127 |
unsigned char |
1 | 0 to 255 |
short |
2 | -32k to 32k |
int |
4 | -2B to 2B |
long |
4 or 8 | platform dependent |
long long |
8 | ± 9 quintillion |
size_t |
4 or 8 | unsigned (for sizes) |
ptrdiff_t |
4 or 8 | signed (pointer difference) |
Use fixed-width types from <stdint.h> when size matters:
#include <stdint.h>
int8_t a; // exactly 8-bit signeduint32_t b; // exactly 32-bit unsignedint_fast32_t c; // fastest at least 32-bitintmax_t d; // largest signed integer| Type | Precision |
|---|---|
float |
~6-7 digits |
double |
~15-16 digits |
long double |
implementation defined |
_Bool flag = 1; // C99 (or use <stdbool.h> → bool, true, false)void *ptr; // generic pointerconst— value cannot be modified through this namevolatile— value may change unexpectedly (hardware, signals)restrict— pointer is the only way to access the object (optimization hint)
int x = 10; // automatic (stack)static int y = 20; // static storage durationextern int z; // declared elsewhereconst int MAX = 100;#define PI 3.14159 // preprocessor constant (no type)Prefer const over #define when a typed constant is possible.
+ - * / % ++ --
== != < > <= >= && || !
& | ^ ~ << >>
= += -= *= /= %= &= |= ^= <<= >>=
sizeof ?: (ternary) , (comma) & (address-of) * (dereference)
Operator precedence tip: When in doubt, use parentheses.
// if / elseif (x > 0) { // ...} else if (x == 0) { // ...} else { // ...}
// switchswitch (code) { case 1: // ... break; case 2: case 3: // fall-through intentional break; default: // ...}
// loopsfor (int i = 0; i < n; i++) { }while (condition) { }do { } while (condition);
// jumpbreak; // exit loop/switchcontinue; // next iterationgoto label; // avoid when possiblereturn value;// Declaration (prototype)int add(int a, int b);
// Definitionint add(int a, int b) { return a + b;}
// No parametersvoid greet(void) { printf("Hello\n");}
// Pass by value (C always copies)void swap(int a, int b); // does NOT swap originals
// Pass by pointer (to modify)void swap(int *a, int *b) { int temp = *a; *a = *b; *b = temp;}int (*fp)(int, int) = add;int result = fp(3, 4);
// Useful for callbacksvoid qsort(void *base, size_t nmemb, size_t size, int (*compar)(const void *, const void *));int arr[5] = {1, 2, 3, 4, 5};int arr[] = {1, 2, 3}; // size inferredint matrix[3][4];
// Array decays to pointervoid print(int *a, size_t n);
// Strings are null-terminated char arrayschar str[] = "hello"; // {'h','e','l','l','o','\0'}char *p = "hello"; // pointer to string literal (read-only)
#include <string.h>strlen(s); // length excluding '\0'strcpy(dest, src); // dangerous if dest too smallstrncpy(dest, src, n); // safer but still needs carestrcmp(s1, s2); // lexicographical comparestrcat(dest, src); // concatenateNever use gets(). Prefer fgets().
int x = 42;int *p = &x; // p holds address of x*p = 100; // modify x through p
int *q = NULL; // null pointerif (q != NULL) { }
// Pointer arithmeticint arr[5] = {10, 20, 30, 40, 50};int *p = arr; // same as &arr[0]*(p + 2) == arr[2]; // 30
// Pointer to pointerint **pp = &p;
// void pointers (generic)void *vp = &x;int *ip = (int *)vp; // cast needed to dereference// Dynamic arrayint *arr = malloc(n * sizeof(int));if (arr == NULL) { /* handle error */ }free(arr);arr = NULL; // good practice after free
// Array of pointerschar *names[] = {"Alice", "Bob", "Charlie"};#include <stdlib.h>
void *malloc(size_t size); // uninitializedvoid *calloc(size_t nmemb, size_t size); // zero-initializedvoid *realloc(void *ptr, size_t size); // resizevoid free(void *ptr);
// Exampleint *data = malloc(100 * sizeof(int));if (!data) { perror("malloc failed"); exit(EXIT_FAILURE);}// use data...free(data);Rules:
- Every
malloc/calloc/reallocneeds a matchingfree. - Do not free the same pointer twice.
- Do not use a pointer after freeing it (dangling pointer).
- Check for
NULLafter allocation.
struct Point { int x; int y;};
struct Point p1 = {10, 20};struct Point p2 = {.x = 5, .y = 15}; // designated initializer (C99)
// Typedef for conveniencetypedef struct { char name[50]; int age;} Person;
Person alice = {"Alice", 30};
// Accessp1.x = 100;Person *ptr = &alice;ptr->age = 31; // equivalent to (*ptr).ageunion Data { int i; float f; char str[20];};enum Color { RED, GREEN, BLUE }; // 0, 1, 2enum Status { OK = 0, ERROR = -1, PENDING = 1 };
enum Color c = GREEN;struct Flags { unsigned int ready : 1; unsigned int error : 1; unsigned int mode : 3;};#define MAX 100#define SQUARE(x) ((x) * (x)) // always parenthesize#define MIN(a,b) ((a) < (b) ? (a) : (b))
#ifdef DEBUG printf("debug info\n");#endif
#if defined(__linux__) // Linux-specific#elif defined(_WIN32) // Windows#else // other#endif
#include <stdio.h> // system header#include "myheader.h" // local header
#undef MAX#pragma once // include guard alternativeHeader guard pattern:
#ifndef MYHEADER_H#define MYHEADER_H
// declarations...
#endif#include <stdio.h>
FILE *fp = fopen("data.txt", "r"); // "r", "w", "a", "rb", "wb", etc.if (fp == NULL) { perror("fopen"); return 1;}
// Character / stringint c = fgetc(fp);fputc('A', fp);fgets(buf, sizeof(buf), fp);fputs("hello\n", fp);
// Formattedfprintf(fp, "%d %s\n", 42, "answer");fscanf(fp, "%d", &x);
// Binaryfread(buffer, sizeof(int), count, fp);fwrite(buffer, sizeof(int), count, fp);
// Positioningfseek(fp, 0, SEEK_END);long size = ftell(fp);rewind(fp);
fclose(fp);| Header | Purpose |
|---|---|
<stdio.h> |
Input/output |
<stdlib.h> |
Memory, conversion, exit, qsort |
<string.h> |
String and memory operations |
<stdint.h> |
Fixed-width integers |
<stdbool.h> |
bool, true, false |
<stddef.h> |
size_t, NULL, offsetof |
<math.h> |
Math functions (link with -lm) |
<time.h> |
Time and date |
<ctype.h> |
Character classification |
<assert.h> |
assert macro |
<errno.h> |
Error codes |
<limits.h> |
Type limits |
<float.h> |
Floating-point limits |
Useful functions:
memcpy,memmove,memset,memcmpatoi/strtol/strtod(preferstrto*family)qsort,bsearchexit,atexitrand/srand(better use modern alternatives in real code)
const int *p; // pointer to const int (can't modify value)int *const p; // const pointer (can't change address)const int *const p; // bothvolatile int *reg = (int *)0x40000000; // memory-mapped registervoid *memcpy(void *restrict dest, const void *restrict src, size_t n);struct Buffer { size_t len; char data[]; // must be last member};int *p = (int[]){1, 2, 3};struct Point p = {.y = 10, .x = 5};#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;}static inline int max(int a, int b) { return a > b ? a : b;}header.h
#ifndef HEADER_H#define HEADER_H
void foo(int x);extern int global_counter;
#endiffile1.c
#include "header.h"
int global_counter = 0;
void foo(int x) { // ...}main.c
#include "header.h"
int main(void) { foo(42); return 0;}Compile: gcc main.c file1.c -o program
| Pitfall | Better Practice |
|---|---|
| Buffer overflows | Always track sizes, use snprintf, bounds-check |
Using gets() |
Use fgets or safer APIs |
Forgetting free |
Pair every allocation with free; tools like Valgrind |
| Dangling pointers | Set pointer to NULL after free |
| Returning pointer to local | Never return address of stack variable |
| Ignoring return values | Check malloc, fopen, etc. |
| Integer overflow | Be careful with sizes and arithmetic |
Assuming int size |
Prefer size_t, stdint.h types |
| Missing includes / prototypes | Enable warnings (-Wall -Wextra) |
Recommended habits:
- Compile with
-Wall -Wextra -Werrorduring development. - Use
constwherever possible. - Prefer
size_tfor sizes and array indices. - Initialize variables.
- Keep functions small and focused.
- Document ownership of pointers (who allocates / who frees).
// Safe string copystrncpy(dest, src, dest_size - 1);dest[dest_size - 1] = '\0';
// Iterate array with pointerfor (int *p = arr; p < arr + n; p++) { printf("%d\n", *p);}
// Swap two values#define SWAP(a, b) do { typeof(a) tmp = (a); (a) = (b); (b) = tmp; } while (0)
// Count elements in static array#define ARRAY_SIZE(a) (sizeof(a) / sizeof((a)[0]))- Official: ISO C standard (C17 / C23 drafts available online)
- Books: The C Programming Language (K&R), C Programming: A Modern Approach (King), Expert C Programming (van der Linden)
- Tools: Valgrind, AddressSanitizer (
-fsanitize=address), clang-tidy, cppcheck - References: cppreference.com (C section), man pages (
man 3 printf)
This cheatsheet targets modern C (C11/C17/C23). Always verify behavior against your compiler and platform.