CC

C cheatsheet – syntax overview

109 key commands and patterns for quick reference.

Skeleton & Compiler Data types & sizes printf format specifiers Input Operators Control flow Arrays & Strings (string.h) Pointers Memory management structs, enum, union, typedef Files & errors Preprocessor & headers Compiler flags & debugging

Skeleton & Compiler

#include <stdio.h> int main(void) { return 0; }Minimal C program
gcc -Wall -Wextra -std=c17 -o prog prog.cCompile with warnings
./progRun the program
/* Block */ // LineComments
#include <file.h> #include "file.h"System header / own header
return 0; EXIT_SUCCESS EXIT_FAILUREEnd the program with a status code

Data types & sizes

char short int long long longIntegers (typically 1, 2, 4, 8, 8 bytes)
unsigned int unsigned charUnsigned integers
float double long doubleFloating-point numbers (typically 4, 8, 16 bytes)
#include <stdbool.h> bool b = true;Boolean values
#include <stdint.h> uint8_t int32_t uint64_tFixed-width integers
size_t ptrdiff_tSizes/indices and pointer differences, respectively
sizeof(x) sizeof(int)Size in bytes (type size_t)
#include <limits.h> INT_MAX INT_MIN CHAR_BITLimits of the types
const int N = 5; enum { MAXN = 100 };Constants

printf format specifiers

%d %i %uint / int / unsigned int
%ld %lld %lu %llulong, long long (also unsigned)
%f %.2f %e %gdouble: default, 2 decimal places, exponent, short
%c %sCharacter / string
%x %X %oHexadecimal (lower/UPPER case), octal
%pPointer (cast the argument to (void *))
%zu %tdsize_t / ptrdiff_t
%5d %-5d %05dWidth 5: right-aligned, left-aligned, zero-padded
%8.3f %.10s %*dWidth 8 with 3 decimals; at most 10 characters; width as argument
%% \n \t \\ \"Percent sign; newline, tab, backslash, double quote

Input

scanf("%d", &n) == 1Read a number (check the return value = values read)
scanf("%lf", &x)Read a double (with scanf: %lf!)
scanf("%31s", puffer)Word with length limit (char puffer[32])
fgets(zeile, sizeof zeile, stdin)Read a whole line safely
zeile[strcspn(zeile, "\n")] = '\0';Remove the newline after fgets
getchar() putchar(c)Read / write a single character (int return value, EOF possible)
strtol(s, &ende, 10) strtod(s, &ende)Safely convert text to a number

Operators

+ - * / %Arithmetic (integer division for int, % = remainder)
== != < > <= >=Comparisons (yield 1 or 0)
&& || !Logical: and, or, not (short-circuit)
& | ^ ~ << >>Bitwise: and, or, xor, not, shift
+= -= *= /= %= &= |= ^= <<= >>=Compound assignments
i++ ++i i-- --iIncrement/decrement (after / before)
a ? b : cTernary operator
(double)x (int)yType conversion (cast)
&x *p p->feld a[i]Address, dereference, field access via pointer, index
sizeof x sizeof(typ)Size in bytes (operator, not a function)

Control flow

if (a) {...} else if (b) {...} else {...}Branching
switch (x) { case 1: ...; break; default: ...; }Multi-way selection (do not forget break)
for (int i = 0; i < n; i++) {...}Counting loop
while (bed) {...}Loop with pre-check
do {...} while (bed);Loop with post-check (at least 1 iteration)
break; continue; return x;Leave the loop / next iteration / end the function
goto ende; ende:Jump (only useful for cleanup code)

Arrays & Strings (string.h)

int a[5] = {0}; int b[] = {1, 2, 3};Create an array / size from initializer
sizeof a / sizeof a[0]Number of elements (real arrays only)
char s[] = "abc"; /* 4 bytes */String as array (with \0)
strlen(s)Length without the null byte
strcmp(a, b)Comparison: 0 = equal, <0 / >0 = less / greater
strcpy(z, q) strcat(z, q)Copy/append (does NOT check the size)
snprintf(z, sizeof z, "%s-%d", s, n)Format and write safely
strchr(s, 'c') strstr(s, "part")Find a character / substring (pointer or NULL)
memcpy(z, q, n) memmove(z, q, n) memset(p, 0, n)Copy bytes / copy overlapping / fill
#include <ctype.h> isdigit isalpha toupper tolowerCharacter classes (argument as unsigned char)

Pointers

int *p = &x;Pointer to x
*p = 5; int y = *p;Write/read a value through the pointer
p->name (*p).nameField access via a pointer to a struct
p + 1 p++ p - qPointer arithmetic (in elements)
a[i] == *(a + i)Indexing is pointer arithmetic
int *p = NULL; if (p != NULL)Set and check a null pointer
const int *p int *const pValue constant / pointer constant
int **pp = &p;Pointer to pointer
int (*fn)(int, int) = add; fn(1, 2);Create and call a function pointer
void *p (int *)pUniversal pointer, cast to the concrete type

Memory management

#include <stdlib.h>Header for malloc, calloc, realloc, free, exit, qsort
int *p = malloc(n * sizeof *p);Allocate memory (uninitialized)
int *p = calloc(n, sizeof *p);Allocate memory filled with 0
tmp = realloc(p, neu * sizeof *p);Change size (store in tmp first, check for NULL)
free(p); p = NULL;Free and reset the pointer
if (p == NULL) { /* error */ }Check every allocation
qsort(a, n, sizeof a[0], vergleich);Sort with a comparison function
exit(EXIT_FAILURE); abort();Terminate the program / abort hard

structs, enum, union, typedef

struct P { int x, y; }; struct P a = {1, 2};Define and initialize a structure
typedef struct { int x, y; } Punkt;Structure with a short type name
Punkt p = {.x = 1, .y = 2};Named initialization (C99)
enum Farbe { ROT, GRUEN, BLAU };Enumeration (0, 1, 2, ...)
union U { int i; float f; };All fields share the memory
offsetof(struct P, y)Byte offset of a field (stddef.h)
static const int N = 3; extern int z;File-internal / defined in another file

Files & errors

FILE *f = fopen("d.txt", "r");Open ("r" read, "w" write, "a" append, +b binary)
fclose(f);Close (always)
fgets(z, sizeof z, f) fputs(s, f)Read a line / write a string
fprintf(f, "%d\n", x) fscanf(f, "%d", &x)Write / read formatted
fread(buf, sz, n, f) fwrite(buf, sz, n, f)Read / write binary
fseek(f, 0, SEEK_END); ftell(f); rewind(f);Set position / get position / back to the start
feof(f) ferror(f) EOFCheck end of file or error (after a read failure)
#include <errno.h> errno perror("text") strerror(errno)Query and print the error cause
stdin stdout stderrStandard streams (errors go to stderr)

Preprocessor & headers

#define N 10Constant as text substitution
#define QUAD(x) ((x) * (x))Function-like macro (always use parentheses)
#ifndef X_H #define X_H ... #endifInclude guard in a header
#ifdef DEBUG ... #endif #if 0 ... #endifConditional compilation / commenting out code
__FILE__ __LINE__ __func__Predefined macros for debugging
#include <assert.h> assert(x > 0);Check an assumption (can be disabled with -DNDEBUG)

Compiler flags & debugging

-Wall -Wextra -WpedanticMany useful warnings
-WerrorTreat warnings as errors
-std=c17Choose the C standard (c11, c17, c23)
-g -O0 -O2 -O3Debug info / no / good / aggressive optimization
-fsanitize=address,undefinedASan + UBSan: find memory errors and UB at runtime
-c -o name -I dir -L dir -lmCompile only / output name / include path / library path / math library
-D DEBUG=1 -E -SDefine a macro / preprocessor only / output assembly
gdb ./prog lldb ./progDebugger (break, run, next, print, bt)
valgrind --leak-check=full ./progFind memory leaks (Linux)
make make cleanBuild the project / clean up (with a Makefile)