Skip to content

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.

Terminal window
# Compile a single file
gcc hello.c -o hello
# Compile with warnings and standards
gcc -Wall -Wextra -std=c17 -O2 hello.c -o hello
# Multi-file project
gcc -c file1.c # produces file1.o
gcc -c file2.c
gcc file1.o file2.o -o program
# Link math library
gcc main.c -lm -o main
# Debug build
gcc -g -O0 main.c -o main

Common flags:

  • -Wall -Wextra — enable useful warnings
  • -std=c11 / -std=c17 / -std=c23 — language standard
  • -O0 to -O3 / -Os — optimization levels
  • -g — debug symbols
  • -I include path, -L library path, -l link library

#include <stdio.h>
int main(void) {
printf("Hello, C!\n");
return 0;
}
  • main returns int (0 = success).
  • Prefer int main(void) over int 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 signed
uint32_t b; // exactly 32-bit unsigned
int_fast32_t c; // fastest at least 32-bit
intmax_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 pointer

  • const — value cannot be modified through this name
  • volatile — 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 duration
extern int z; // declared elsewhere
const 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 / else
if (x > 0) {
// ...
} else if (x == 0) {
// ...
} else {
// ...
}
// switch
switch (code) {
case 1:
// ...
break;
case 2:
case 3:
// fall-through intentional
break;
default:
// ...
}
// loops
for (int i = 0; i < n; i++) { }
while (condition) { }
do { } while (condition);
// jump
break; // exit loop/switch
continue; // next iteration
goto label; // avoid when possible
return value;

// Declaration (prototype)
int add(int a, int b);
// Definition
int add(int a, int b) {
return a + b;
}
// No parameters
void 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 callbacks
void 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 inferred
int matrix[3][4];
// Array decays to pointer
void print(int *a, size_t n);
// Strings are null-terminated char arrays
char 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 small
strncpy(dest, src, n); // safer but still needs care
strcmp(s1, s2); // lexicographical compare
strcat(dest, src); // concatenate

Never 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 pointer
if (q != NULL) { }
// Pointer arithmetic
int arr[5] = {10, 20, 30, 40, 50};
int *p = arr; // same as &arr[0]
*(p + 2) == arr[2]; // 30
// Pointer to pointer
int **pp = &p;
// void pointers (generic)
void *vp = &x;
int *ip = (int *)vp; // cast needed to dereference

// Dynamic array
int *arr = malloc(n * sizeof(int));
if (arr == NULL) { /* handle error */ }
free(arr);
arr = NULL; // good practice after free
// Array of pointers
char *names[] = {"Alice", "Bob", "Charlie"};

#include <stdlib.h>
void *malloc(size_t size); // uninitialized
void *calloc(size_t nmemb, size_t size); // zero-initialized
void *realloc(void *ptr, size_t size); // resize
void free(void *ptr);
// Example
int *data = malloc(100 * sizeof(int));
if (!data) {
perror("malloc failed");
exit(EXIT_FAILURE);
}
// use data...
free(data);

Rules:

  • Every malloc/calloc/realloc needs a matching free.
  • Do not free the same pointer twice.
  • Do not use a pointer after freeing it (dangling pointer).
  • Check for NULL after allocation.

struct Point {
int x;
int y;
};
struct Point p1 = {10, 20};
struct Point p2 = {.x = 5, .y = 15}; // designated initializer (C99)
// Typedef for convenience
typedef struct {
char name[50];
int age;
} Person;
Person alice = {"Alice", 30};
// Access
p1.x = 100;
Person *ptr = &alice;
ptr->age = 31; // equivalent to (*ptr).age

union Data {
int i;
float f;
char str[20];
};

enum Color { RED, GREEN, BLUE }; // 0, 1, 2
enum 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 alternative

Header 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 / string
int c = fgetc(fp);
fputc('A', fp);
fgets(buf, sizeof(buf), fp);
fputs("hello\n", fp);
// Formatted
fprintf(fp, "%d %s\n", 42, "answer");
fscanf(fp, "%d", &x);
// Binary
fread(buffer, sizeof(int), count, fp);
fwrite(buffer, sizeof(int), count, fp);
// Positioning
fseek(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, memcmp
  • atoi / strtol / strtod (prefer strto* family)
  • qsort, bsearch
  • exit, atexit
  • rand / 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; // both

volatile int *reg = (int *)0x40000000; // memory-mapped register

void *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;
#endif

file1.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 -Werror during development.
  • Use const wherever possible.
  • Prefer size_t for sizes and array indices.
  • Initialize variables.
  • Keep functions small and focused.
  • Document ownership of pointers (who allocates / who frees).

// Safe string copy
strncpy(dest, src, dest_size - 1);
dest[dest_size - 1] = '\0';
// Iterate array with pointer
for (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.

You're offline Check your connection.