📖 Guide
C — Complete Reference
Comprehensive C programming cheat sheet covering syntax, pointers, memory management, and standard library functions.
98 commands across 12 categories
BasicsData TypesOperatorsControl FlowFunctionsPointersArrays & StringsStructsMemory ManagementFile I/OPreprocessorCommon Library Functions
Basics
| Command | Description |
|---|---|
#include <stdio.h> | Include standard I/O library |
int main(void) { return 0; } | Minimal C program entry point |
int x = 10; | Declare and initialize a variable |
const int MAX = 100; | Declare a constant variable |
printf("Hello %s\n", name); | Print formatted output to stdout |
scanf("%d", &x); | Read formatted input from stdin |
// comment /* block */ | Single-line (C99+) and multi-line comments |
typedef unsigned long ulong; | Create a type alias |
Data Types
| Command | Description |
|---|---|
char c = 'A'; | Single character (1 byte) |
int n = 42; | Integer (typically 4 bytes) |
float f = 3.14f; | Single-precision floating point |
double d = 3.14159; | Double-precision floating point |
long long ll = 9000000000LL; | At least 64-bit integer |
unsigned int u = 255; | Non-negative integer |
_Bool b = 1; // or #include <stdbool.h> | Boolean type (C99+, use bool with stdbool.h) |
size_t len = sizeof(arr); | Unsigned type for sizes and counts |
void | No type — used for functions with no return or generic pointers |
Operators
| Command | Description |
|---|---|
+ - * / % | Arithmetic operators (% is modulo, integer only) |
== != < > <= >= | Comparison operators |
&& || ! | Logical AND, OR, NOT |
& | ^ ~ << >> | Bitwise AND, OR, XOR, NOT, shifts |
+= -= *= /= %= | Compound assignment operators |
++i i++ --i i-- | Pre/post increment and decrement |
condition ? a : b | Ternary conditional operator |
sizeof(type)e.g. sizeof(int) // typically 4 | Get size in bytes of a type or variable |
Control Flow
| Command | Description |
|---|---|
if (cond) { } else if { } else { } | Conditional branching |
switch (val) { case 1: ...; break; default: ...; } | Multi-way branching (don't forget break!) |
for (int i = 0; i < n; i++) { } | For loop with counter |
while (cond) { } | While loop — checks condition before each iteration |
do { } while (cond); | Do-while loop — runs body at least once |
break; | Exit the innermost loop or switch |
continue; | Skip to next iteration of the loop |
goto label; label: ... | Jump to a labeled statement (use sparingly) |
Functions
| Command | Description |
|---|---|
int add(int a, int b) { return a + b; } | Define a function with return type and parameters |
void greet(const char *name); | Function prototype (declaration without body) |
static int helper(void) { } | Static function — visible only within its file |
inline int square(int x) { return x*x; } | Inline function hint (C99+) |
int sum(int n, ...) { } | Variadic function (use <stdarg.h> macros inside) |
void modify(int *ptr) { *ptr = 5; } | Pass by pointer to modify caller's variable |
int (*fptr)(int, int) = &add;e.g. int result = fptr(2, 3); // 5 | Function pointer declaration and assignment |
Pointers
| Command | Description |
|---|---|
int *p = &x; | Declare pointer and assign address of x |
*p = 10; | Dereference — write to the pointed-to value |
int val = *p; | Dereference — read the pointed-to value |
int **pp = &p; | Pointer to pointer (double indirection) |
void *generic; | Generic pointer — can point to any type (must cast to use) |
NULL | Null pointer constant (pointer that points nowhere) |
p + 1 | Pointer arithmetic — advances by sizeof(*p) bytes |
arr[i] ≡ *(arr + i) | Array indexing is pointer arithmetic |
Arrays & Strings
| Command | Description |
|---|---|
int arr[5] = {1, 2, 3, 4, 5}; | Declare and initialize a fixed-size array |
int arr[] = {1, 2, 3}; | Array with size inferred from initializer |
int matrix[3][4]; | 2D array (3 rows, 4 columns) |
char str[] = "hello"; | String as null-terminated char array |
strlen(str) | Get string length (not counting '\0') |
strcpy(dest, src) | Copy string src to dest |
strcmp(a, b) | Compare strings (0 = equal, <0 or >0 otherwise) |
strcat(dest, src) | Append src to end of dest |
strncpy(dest, src, n) | Copy at most n characters (safer than strcpy) |
Structs
| Command | Description |
|---|---|
struct Point { int x; int y; }; | Define a struct type |
struct Point p = {10, 20}; | Declare and initialize a struct variable |
p.x | Access struct member with dot operator |
ptr->x | Access member through pointer (same as (*ptr).x) |
typedef struct { int x; int y; } Point; | Typedef struct for cleaner usage |
struct Node { int val; struct Node *next; }; | Self-referential struct (linked list) |
union Data { int i; float f; char c; }; | Union — members share the same memory |
enum Color { RED, GREEN, BLUE }; | Enumeration — named integer constants |
Memory Management
| Command | Description |
|---|---|
malloc(n * sizeof(int))e.g. int *arr = malloc(10 * sizeof(int)); | Allocate n ints on heap (returns void*) |
calloc(n, sizeof(int)) | Allocate and zero-initialize memory |
realloc(ptr, new_size) | Resize previously allocated block |
free(ptr); | Free heap-allocated memory (always free what you malloc!) |
ptr = NULL; | Set pointer to NULL after freeing to avoid dangling pointer |
memset(ptr, 0, n) | Fill memory with a byte value |
memcpy(dest, src, n) | Copy n bytes from src to dest (no overlap allowed) |
memmove(dest, src, n) | Copy n bytes — safe for overlapping regions |
File I/O
| Command | Description |
|---|---|
FILE *f = fopen("file.txt", "r"); | Open file ("r" read, "w" write, "a" append, "rb" binary) |
fclose(f); | Close an open file |
fgets(buf, size, f) | Read a line into buffer |
fprintf(f, "x=%d\n", x); | Write formatted output to file |
fscanf(f, "%d", &x); | Read formatted input from file |
fread(buf, size, count, f) | Read binary data from file |
fwrite(buf, size, count, f) | Write binary data to file |
feof(f) | Check if end-of-file has been reached |
fseek(f, offset, SEEK_SET) | Move file position indicator |
Preprocessor
| Command | Description |
|---|---|
#include <header.h> | Include system header |
#include "myfile.h" | Include local/project header |
#define PI 3.14159 | Define a macro constant |
#define MAX(a,b) ((a)>(b)?(a):(b)) | Define a macro function (parenthesize args!) |
#ifdef DEBUG ... #endif | Conditional compilation — include if macro defined |
#ifndef HEADER_H\n#define HEADER_H\n...\n#endif | Include guard — prevent double inclusion |
#pragma once | Non-standard but widely supported include guard |
__FILE__ __LINE__ __func__ | Built-in macros for file, line number, function name |
Common Library Functions
| Command | Description |
|---|---|
abs(n) fabs(x) | Absolute value for int (stdlib) and double (math) |
pow(base, exp) sqrt(x) | Power and square root (math.h) |
rand() % n | Random int in [0, n) — seed with srand(time(NULL)) |
atoi(str) atof(str) | Convert string to int/double |
qsort(arr, n, size, cmp)e.g. int cmp(const void *a, const void *b) { return *(int*)a - *(int*)b; } | Sort array using quicksort |
bsearch(&key, arr, n, size, cmp) | Binary search in sorted array |
exit(EXIT_SUCCESS) | Terminate program with status code |
assert(condition) | Abort if condition is false (assert.h, disabled with NDEBUG) |
📖 Free, searchable command reference. Bookmark this page for quick access.