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;
}

Comments

// Single-line comment (C99+)

/* Multi-line
   comment */

/* Comments do NOT nest — /* this breaks */ rest is NOT commented */

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

KeywordScopeLifetimeDefault init
autoblock (local)blockundefined
staticblock or fileprogramzero
externfile-visibleprogramzero
registerblockblockundefined
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

QualifierMeaning
constValue cannot be modified
volatileValue may change externally; suppress optimization
restrictPointer is sole alias for its object (C99+)
_AtomicAtomic 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

SpecifierTypeNotes
%d, %iintsigned decimal
%uunsigned intunsigned decimal
%ldlong
%lldlong long
%luunsigned long
%fdouble (printf) / float * (scanf)
%lfdouble * (scanf)
%e, %Escientific notation
%gshorter of %f/%e
%cchar
%schar * (null-terminated)
%ppointer address
%x, %Xhex integer
%ooctal integer
%zusize_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

KeywordPurpose
autodefault storage class (local)
breakexit loop or switch
caselabel in switch
charcharacter type
constread-only qualifier
continuenext loop iteration
defaultdefault case in switch
dodo-while loop
doubledouble-precision float
elsealternative branch
enumenumeration type
externexternal linkage declaration
floatsingle-precision float
forfor loop
gotounconditional jump
ifconditional
inlineinline function hint (C99+)
intinteger type
longextended integer/float
registerregister storage hint
restrictno-alias pointer hint (C99+)
returnreturn value from function
shortshorter integer
signedexplicit signed integer
sizeofcompile-time size in bytes
staticstatic storage / internal linkage
structstructure type
switchmulti-branch selection
typedeftype alias
unionoverlapping storage type
unsignedunsigned integer
voidno type / omitted return
volatilesuppress optimization
whilewhile loop
_Boolboolean type (C99+)
_Complexcomplex number (C99+)
_Noreturnfunction never returns (C11+)
_Static_assertcompile-time assertion (C11+)
_Alignas, _Alignofalignment control (C11+)
_Generictype-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,undefined to 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