C Cheat Sheet
The C programming language is a foundational, low-level language used for operating systems, embedded systems, performance‑critical software, and systems programming. This C cheatsheet provides a structured reference for C syntax, pointers, memory management, data structures, and common programming patterns.
Compilation
gcc main.c -o app
./app
gcc -g -Wall -Wextra main.c -o app
gcc -std=c11 main.c -o app
Basic Program Structure
#include <stdio.h>
int main(void) {
printf("Hello, world\n");
return 0;
}
Data Types
int integer_value = 10;
float float_value = 3.14f;
double double_value = 3.14159;
char character = 'A';
Sizes
sizeof(int);
sizeof(double);
sizeof(char);
Exact-width integers
#include <stdint.h>
int8_t a;
int32_t b;
uint64_t c;
Variables & Constants
int count = 0;
const int max_value = 100;
#define PI 3.14159
Operators
a + b
a - b
a * b
a / b
a % b
a == b
a != b
a > b
a < b
a && b
a || b
!a
Control Flow
if (value > 10) {
result = 1;
} else {
result = 0;
}
switch (value) {
case 1:
break;
case 2:
break;
default:
break;
}
for (int i = 0; i < 5; i++) {
printf("%d\n", i);
}
while (count > 0) {
count--;
}
Functions
int add(int a, int b) {
return a + b;
}
Function prototypes
int add(int a, int b);
Arrays
int numbers[3] = {1, 2, 3};
for (int i = 0; i < 3; i++) {
printf("%d\n", numbers[i]);
}
Pointers
int value = 10;
int *ptr = &value;
*ptr = 20;
Pointer basics
&→ address of*→ dereference
printf("%p\n", (void*)ptr);
Pointer Arithmetic
int values[3] = {1, 2, 3};
int *p = values;
p++;
printf("%d\n", *p);
Out-of-bounds
Pointer arithmetic outside array bounds causes undefined behavior.
Strings
#include <string.h>
char text[16] = "hello";
strlen(text);
strcpy(text, "hi");
strcmp(text, "hi");
Null-terminated
C strings must end with '\0'.
Structs
struct Point {
int x;
int y;
};
struct Point p = {10, 20};
p.x = 5;
struct Point *ptr = &p;
ptr->y = 15;
Enums
enum Status {
STATUS_OK,
STATUS_ERROR
};
Memory Management
#include <stdlib.h>
int *data = malloc(sizeof(int) * 10);
if (data == NULL) {
return 1;
}
free(data);
calloc vs malloc
int *arr = calloc(10, sizeof(int));
Memory leaks
Every malloc / calloc must have a matching free.
File I/O
#include <stdio.h>
FILE *file = fopen("data.txt", "r");
if (file != NULL) {
fclose(file);
}
fprintf(file, "text\n");
fscanf(file, "%d", &value);
Header Files
// math_utils.h
int add(int a, int b);
// math_utils.c
#include "math_utils.h"
int add(int a, int b) {
return a + b;
}
Preprocessor
#define DEBUG 1
#if DEBUG
printf("debug mode\n");
#endif
Common Low-Level Patterns
int tmp = a;
a = b;
b = tmp;
memset(buffer, 0, size);
for (;;) {
break;
}