C Cheatsheet
Basics
Use this C reference while you build software engineering projects, review code for technical interview prep, or polish examples for a software engineer resume.
C Cheatsheet for CS Fundamentals
Use this C cheatsheet as a quick companion to a computer science curriculum, systems course, or teach-yourself-CS plan. It covers the syntax and memory model that show up in university-level coding courses: program structure, types, pointers, arrays, structs, manual allocation, files, and the preprocessor. When you want to test a snippet, open the online C compiler; when you want the full course path, start with the free CS curriculum.
Program Structure
Every C program has at least one function: main. Execution begins there.
#include <stdio.h> // standard I/O header #include <stdlib.h> // malloc, free, exit, etc. int main(void) { printf("Hello, world!\n"); return 0; // 0 = success } // With command-line arguments int main(int argc, char *argv[]) { // argc: count including program name // argv[0]: program name, argv[1..argc-1]: arguments printf("Program: %s, args: %d\n", argv[0], argc - 1); return 0; }
Variables and Declaration
int x; // declaration (uninitialized — value is undefined) int y = 10; // declaration + initialization int a, b, c; // multiple declarations of same type int n = 5, m = 3; // Constants — must be initialized, cannot be modified const int MAX = 100; const double PI = 3.14159265358979;
Storage Classes
| Keyword | Scope | Lifetime | Default init |
|---|---|---|---|
auto | block (local) | block | undefined |
static | block or file | program | zero |
extern | file-visible | program | zero |
register | block | block | undefined |
static int call_count = 0; // persists between calls; initialized once extern int global_var; // defined in another translation unit void counter(void) { static int n = 0; // initialized once, persists across calls n++; }
Type Qualifiers
| Qualifier | Meaning |
|---|---|
const | Value cannot be modified |
volatile | Value may change externally; suppress optimization |
restrict | Pointer is sole alias for its object (C99+) |
_Atomic | Atomic read/write (C11+) |
volatile int timer_count; // do not optimize away reads const volatile int hw_status; // read-only hardware register void copy(int * restrict dst, const int * restrict src, size_t n);
Basic Input / Output
#include <stdio.h> // Output printf("integer: %d, float: %.2f, char: %c, string: %s\n", 42, 3.14, 'A', "hi"); fprintf(stderr, "Error: %s\n", "something failed"); putchar('A'); puts("a string with automatic newline"); // Input int n; scanf("%d", &n); // & required — passes address scanf("%d %d", &a, &b); char buf[128]; scanf("%127s", buf); // safe: limit to buffer - 1 fgets(buf, sizeof(buf), stdin); // preferred for lines; includes '\n' int c = getchar(); // reads one char (returns int for EOF check)
Format Specifiers
| Specifier | Type | Notes |
|---|---|---|
%d, %i | int | signed decimal |
%u | unsigned int | unsigned decimal |
%ld | long | |
%lld | long long | |
%lu | unsigned long | |
%f | double (printf) / float * (scanf) | |
%lf | double * (scanf) | |
%e, %E | scientific notation | |
%g | shorter of %f/%e | |
%c | char | |
%s | char * (null-terminated) | |
%p | pointer address | |
%x, %X | hex integer | |
%o | octal integer | |
%zu | size_t | |
%% | literal % |
Width and precision:
printf("%10d", 42); // right-aligned, field width 10 printf("%-10d", 42); // left-aligned printf("%010d", 42); // zero-padded printf("%.2f", 3.14159); // 2 decimal places → 3.14 printf("%8.3f", 3.14159); // width 8, 3 decimals printf("%.*f", prec, x); // precision from argument printf("%+d", 42); // force sign: +42 printf("% d", 42); // space before positive: " 42"
Scope and Lifetime
int global = 0; // file scope; lives entire program void foo(void) { int local = 1; // block scope; stack lifetime { int inner = 2; // inner block scope } // inner not accessible here static int s = 0; // block scope but static (program) lifetime s++; }
File-scope static limits visibility to the current translation unit (internal linkage):
static int helper(void) { return 42; } // not visible outside this .c file
Keywords Reference
| Keyword | Purpose |
|---|---|
auto | default storage class (local) |
break | exit loop or switch |
case | label in switch |
char | character type |
const | read-only qualifier |
continue | next loop iteration |
default | default case in switch |
do | do-while loop |
double | double-precision float |
else | alternative branch |
enum | enumeration type |
extern | external linkage declaration |
float | single-precision float |
for | for loop |
goto | unconditional jump |
if | conditional |
inline | inline function hint (C99+) |
int | integer type |
long | extended integer/float |
register | register storage hint |
restrict | no-alias pointer hint (C99+) |
return | return value from function |
short | shorter integer |
signed | explicit signed integer |
sizeof | compile-time size in bytes |
static | static storage / internal linkage |
struct | structure type |
switch | multi-branch selection |
typedef | type alias |
union | overlapping storage type |
unsigned | unsigned integer |
void | no type / omitted return |
volatile | suppress optimization |
while | while loop |
_Bool | boolean type (C99+) |
_Complex | complex number (C99+) |
_Noreturn | function never returns (C11+) |
_Static_assert | compile-time assertion (C11+) |
_Alignas, _Alignof | alignment control (C11+) |
_Generic | type-generic expression (C11+) |
Compilation Model
source.c → preprocessor → compiler → assembler → linker → executable
# Compile and link gcc -std=c17 -Wall -Wextra -o program source.c # Separate compile then link gcc -std=c17 -c source.c -o source.o gcc source.o -o program # Multiple source files gcc -std=c17 -o prog main.c util.c -lm # Useful flags # -O0 / -O1 / -O2 / -O3 / -Os optimization levels # -g debug symbols # -fsanitize=address,undefined runtime error detection # -Werror warnings as errors # -pedantic strict standard conformance # -DNDEBUG disable assert()
Undefined Behavior — Common Sources
UB allows the compiler to do anything, including silently wrong behavior. Use
-fsanitize=address,undefinedto catch it.
- Reading an uninitialized variable
- Signed integer overflow (
INT_MAX + 1) - Null or dangling pointer dereference
- Out-of-bounds array access
- Use after
free - Modifying a string literal (
char *s = "hi"; s[0] = 'H';) - Violating strict aliasing rules
- Shifting by value >= width of type
- Returning a pointer to a local variable
Comments