Skip to content
Tutorials Center
My learning

Topics

Lesson 128 of 135 ยท Practice and Review

C Cheat Sheet

A dense one-page C reference - types, printf and scanf formats, operator precedence, control flow, functions, pointers, memory, strings, structs, the preprocessor, files and headers.

This page compresses the whole C course into one dense reference: the syntax, types, format specifiers, library functions and idioms you reach for every day, in short snippets you can scan in seconds. Keep it open while you work through the practice exercises and the classic C programs, while you write your own code, or the evening before an interview.

The core here is portable C99/C11/C17 that every compiler accepts; features that need C23 are labeled. Our editors compile with GCC 15 as gcc -std=c23 -Wall -Wextra. Each section links to the lesson that explains the topic properly, and the items that trip people up most come with live editors, so you can run them and watch the behavior.

Program basics

Skeleton, output and input

C
#include <stdio.h>      /* printf, puts, fgets, FILE */
#include <stdlib.h>     /* malloc, free, exit, strtol, qsort */

int main(void)
{
    printf("Hello, %s! %d + %d = %d\n", "world", 2, 3, 2 + 3);
    puts("puts adds the newline for you");
    fprintf(stderr, "errors and diagnostics go to stderr\n");

    char line[100];
    if (fgets(line, sizeof line, stdin) != NULL) {   /* safe: never overflows */
        char *end;
        long n = strtol(line, &end, 10);             /* end shows where parsing stopped */
        if (end != line) {
            printf("you typed %ld\n", n);
        }
    }
    return EXIT_SUCCESS;                             /* 0; EXIT_FAILURE on error */
}

Build outside our editor: gcc -std=c17 -Wall -Wextra -g main.c -o app (add -lm when you use <math.h>), then ./app. See Getting Started, How C Works, printf and Reading Input.

Basic types

Type Typical size (64-bit Linux) Literals Notes
char 1 byte 'A', '\n', '\0' signedness is implementation-defined
short 2 bytes at least 16 bits
int 4 bytes 42, 052 (octal), 0x2A at least 16 bits
long 8 bytes (4 on Windows) 42L at least 32 bits
long long 8 bytes 42LL, 42ULL at least 64 bits
unsigned 4 bytes 42u wraps around modulo 2N
float 4 bytes 3.14f about 7 significant digits
double 8 bytes 3.14, 1e-9 about 15โ€“16 digits; the default
long double 16 bytes (x86-64) 3.14L platform-dependent
bool 1 byte true, false <stdbool.h>; keywords in C23
size_t 8 bytes sizeof x unsigned; sizes and indexes
int32_t, uint8_t, โ€ฆ exact <stdint.h>

Only sizeof(char) == 1 is guaranteed; check the rest with sizeof and <limits.h> (INT_MAX, LLONG_MAX, CHAR_BIT, SIZE_MAX). C23 adds binary literals 0b1010 and digit separators 1'000'000. See Data Types, Integer Types, Floating-Point Numbers, Characters, Booleans and Type Limits.

Variables and constants

C
int count = 0;                      /* always initialize locals: garbage otherwise */
const double tax_rate = 0.2;        /* read-only variable */
#define BUFFER_SIZE 256             /* preprocessor text substitution, no type */
enum { MAX_USERS = 100 };           /* a typed int constant, usable in array sizes */
constexpr int max_items = 50;       /* C23: a true compile-time constant */
static int calls;                   /* file scope or static: zero-initialized */
typedef unsigned long ulong;        /* a type alias */
typeof(count) other = 1;            /* C23: the type of an expression */
auto ratio = 0.5;                   /* C23: type inferred (double) */

See Variables, Constants, typedef and Scope and Storage Classes.

printf and scanf formats

Specifier printf argument scanf argument
%d, %i int int * (%i also reads 0x1F, 017)
%u unsigned unsigned *
%ld, %lld long, long long long *, long long *
%hhd, %hd signed char, short pointers to them
%zu size_t size_t *
%td ptrdiff_t ptrdiff_t *
%x, %X, %o unsigned in hex or octal unsigned *
%f, %e, %g double (a float is promoted) float *
%lf double (same as %f) double *
%Lf long double long double *
%a double in hex floating point
%c int (a character) char * (doesn't skip spaces: use " %c")
%s char * (null-terminated) char *; always give a width: %99s
%p void *
%% a literal %

Exact-width types use macros from <inttypes.h>: printf("%" PRId64 "\n", value), PRIu32, PRIx64, SCNd32. C23 also adds %b for binary output, but C libraries are still catching up (ours prints it literally), so don't rely on it yet.

Flags, width and precision: %-8s left-aligns in 8 columns, %08.3f pads with zeros to 8 characters with 3 decimals, %+d always shows the sign, %#x adds 0x, %.5s prints at most 5 characters, and %*d takes the width from an argument. scanf returns the number of items it converted (or EOF): always check it.

C Format specifiers in action

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

See Printing Output with printf and Reading Input with scanf and fgets.

Operators

Precedence, highest first

Level Operators Associativity
1 () call, [], ., ->, postfix ++ -- left to right
2 prefix ++ --, unary + -, !, ~, (type), *, &, sizeof, alignof right to left
3 * / % left to right
4 + - left to right
5 << >> left to right
6 < <= > >= left to right
7 == != left to right
8 & left to right
9 ^ left to right
10 | left to right
11 && left to right
12 || left to right
13 ?: right to left
14 = += -= *= /= %= <<= >>= &= ^= |= right to left
15 , left to right

Classic traps: flags & MASK == 0 means flags & (MASK == 0); *p++ increments the pointer, not the value ((*p)++ does that); a < b < c compares the 0-or-1 result of a < b with c. When in doubt, add parentheses. See Operator Precedence.

Quick facts

C
7 / 2        /* 3: integer division truncates toward zero */
-7 / 2       /* -3 */
-7 % 2       /* -1: the remainder takes the sign of the left operand */
7 / 2.0      /* 3.5: one double operand makes it floating point */
x / 0        /* undefined behavior for integers; inf or NaN for doubles */
i++          /* value before incrementing; ++i is the value after */
i = i++;     /* undefined behavior: i modified twice without sequencing */
a && b       /* b is evaluated only if a is true (short-circuit) */
x ? y : z    /* y if x is nonzero, else z */
1u << 31     /* shift unsigned values; shifting into the sign bit of int is UB */
x & (x - 1)  /* clears the lowest set bit; == 0 tests for a power of two (x > 0) */

Comparisons and ! yield the int 0 or 1. Any nonzero value is true. See Arithmetic, Assignment and Increment, Comparison and Logical Operators and Bitwise Operators.

Control flow

C
if (score >= 90) {
    grade = 'A';
} else if (score >= 80) {
    grade = 'B';
} else {
    grade = 'C';
}

switch (command) {              /* integer types and enums only, not strings */
case 'q':
    running = false;
    break;                      /* without break, execution falls through */
case 'h':
    show_help();
    [[fallthrough]];            /* C23: intentional fall-through, no warning */
case 'v':
    show_version();
    break;
default:
    puts("unknown command");
}

for (int i = 0; i < n; i++) { }         /* loop variable scoped to the loop (C99) */
while (fgets(line, sizeof line, stdin) != NULL) { }
do { } while (again);                   /* body runs at least once */

break;      /* leave the innermost loop or switch */
continue;   /* skip to the next iteration */
goto cleanup;   /* the accepted use: jump to shared cleanup code */

See if and else, switch, while Loops, for Loops and break, continue and goto.

Functions

C
int add(int a, int b);                  /* prototype (declaration), usually in a .h */
void greet(void);                       /* (void): no parameters; () meant "unspecified" before C23 */

int add(int a, int b)                   /* definition */
{
    return a + b;                       /* arguments are passed BY VALUE (copies) */
}

void swap(int *a, int *b)               /* pointers let a function change the caller's data */
{
    int tmp = *a;
    *a = *b;
    *b = tmp;
}

static int helper(int x) { return x * 2; }          /* static: private to this file */
static inline int square(int x) { return x * x; }   /* small helper for headers */

int sum(int count, ...);                /* variadic: va_list, va_start, va_arg, va_end */
long factorial(int n) { return n <= 1 ? 1 : n * factorial(n - 1); }   /* recursion */

int (*operation)(int, int) = add;       /* function pointer */
typedef int (*binary_op)(int, int);     /* readable alias */
int result = operation(2, 3);           /* call through it: 5 */

A function can't return an array, but it can return a struct, and it must never return a pointer to one of its local variables. See Functions, Parameters and Return Values, Prototypes and Headers, Recursion, Variadic Functions, inline and Function Pointers.

Arrays and strings

C
int scores[5] = {90, 85, 77};           /* the rest are 0 */
int lookup[10] = {[3] = 1, [7] = 2};    /* designated initializers (C99) */
size_t n = sizeof scores / sizeof scores[0];   /* 5; only works on a real array */
int grid[3][4];                         /* 3 rows of 4 ints, row-major */
void print_grid(int rows, int cols, int g[rows][cols]);   /* VLA parameter */

char name[16] = "Ada";                  /* array: 'A' 'd' 'a' '\0' + zeros, modifiable */
const char *title = "Dr.";              /* points to a read-only string literal */

Arrays are not bounds-checked: scores[5] is undefined behavior. A string is a char array ending in '\0', so it needs length + 1 bytes.

<string.h> function Does Watch out
strlen(s) length without the '\0' O(n) each call; returns size_t
strcpy(d, s), strcat(d, s) copy, append no size check: prefer snprintf
strncpy(d, s, n) copy at most n may leave d unterminated
strcmp(a, b) <0, 0, >0 never compare strings with ==
strncmp(a, b, n) compare first n chars
strchr(s, c), strrchr first/last c returns NULL if absent
strstr(s, sub) find a substring
strtok(s, delims) split into tokens modifies s, not reentrant
strcspn(s, set) length before any char of set s[strcspn(s, "\n")] = '\0' strips a newline
memcpy(d, s, n) copy bytes regions must not overlap
memmove(d, s, n) copy bytes overlap is fine
memset(p, v, n) fill bytes sets bytes, not ints
memcmp(a, b, n) compare bytes
strdup(s), memccpy heap copy; bounded copy C23 (and POSIX); not in every library yet
C
snprintf(buf, sizeof buf, "%s-%d", name, id);   /* the safe way to build strings */
long v = strtol(text, &end, 10);                /* check end and errno, not atoi */
double d = strtod(text, &end);
int matched = sscanf(line, "%d %d", &a, &b);    /* parse from a string */

Never use gets (removed in C11). See Arrays, Multidimensional Arrays, Strings, String Functions, Safe String Handling and Converting Strings and Numbers.

Pointers

C
int x = 10;
int *p = &x;            /* p holds the address of x */
*p = 20;                /* dereference: x is now 20 */
int *none = NULL;       /* or nullptr in C23; never dereference it */
printf("%p\n", (void *)p);

int a[4] = {1, 2, 3, 4};
int *q = a;             /* array decays to &a[0] */
q[2] == *(q + 2);       /* indexing IS pointer arithmetic */
ptrdiff_t gap = &a[3] - &a[0];   /* 3 elements apart */
int *end = a + 4;       /* one past the end: valid to form and compare, not to dereference */

int **pp = &p;          /* pointer to pointer: lets a function change the caller's pointer */
const int *ro = &x;     /* can't change *ro through ro */
int *const fixed = &x;  /* can't change where fixed points */
void *any = &x;         /* generic pointer; convert back before use */
void copy(int *restrict dst, const int *restrict src, size_t n);   /* no aliasing promise */

Read declarations right to left: const char *const s is "s is a const pointer to const char". See Pointers, Pointer Arithmetic, Pointers and Arrays, Pointers to Pointers, const and Pointers, void Pointers and Pointers and Functions.

C Pointers, arrays and sizeof

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

GCC warns about sizeof values inside show, and that warning is the point of the example: an array parameter is a pointer, so sizeof can't recover the length. Pass the count separately.

Dynamic memory

C
int *nums = malloc(count * sizeof *nums);      /* sizeof *p: right even if the type changes */
if (nums == NULL) { /* handle out of memory */ }

int *zeros = calloc(count, sizeof *zeros);     /* zeroed, and checks count * size overflow */

int *bigger = realloc(nums, new_count * sizeof *nums);
if (bigger == NULL) { free(nums); /* handle */ }   /* never nums = realloc(nums, ...) */
else { nums = bigger; }

free(nums);           /* exactly once per allocation */
nums = NULL;          /* optional, prevents accidental reuse */
Bug What happens
Memory leak allocated memory is never freed
Use after free reading or writing freed memory: UB
Double free freeing the same pointer twice: UB, often a crash
Buffer overrun writing past the end of a block: UB, a security hole
Uninitialized read malloc memory and locals start as garbage
Dangling pointer returning &local from a function

Find these with -fsanitize=address,undefined or Valgrind. See Dynamic Memory, Memory Errors, Memory Layout and Building a Dynamic Array.

Structures, unions and enums

C
typedef struct {
    char name[32];
    int age;
    double score;
} student;

student s = {.name = "Lin", .age = 20};     /* designated initializers; score is 0 */
student copy = s;                           /* structs copy with = (arrays don't) */
student *ps = &s;
ps->age++;                                  /* same as (*ps).age++ */
s = (student){.name = "Max", .age = 22};    /* compound literal (C99) */

struct node {                               /* self-referential: needs the tag */
    int value;
    struct node *next;
};

typedef enum { RED, GREEN, BLUE } color;    /* 0, 1, 2 */
enum flags : unsigned char { BOLD = 1, ITALIC = 2 };   /* C23: fixed underlying type */

typedef struct {
    enum { INT_VALUE, TEXT_VALUE } kind;    /* tagged union: the tag says which member is live */
    union {
        int number;
        char text[16];
    } as;
} value;

struct packed_flags { unsigned ready : 1; unsigned mode : 3; };   /* bit-fields */

sizeof a struct can exceed the sum of its members because of padding; offsetof(type, member) from <stddef.h> gives a member's position, and alignof/alignas query and set alignment (keywords in C23, macros from <stdalign.h> in C11). See Structures, Structures and Pointers, Arrays of Structures, Unions, Enumerations, Bit-Fields and Padding and Alignment.

C Structs, malloc and qsort together

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

The comparator returns (x < y) - (x > y) instead of y - x: subtraction can overflow for large values, while the comparison trick always yields -1, 0 or 1.

The preprocessor

C
#include <stdio.h>          /* system header */
#include "inventory.h"      /* your header: searched next to the source file first */

#define PI 3.14159
#define SQUARE(x) ((x) * (x))            /* parenthesize every argument and the whole */
#define SWAP(a, b) do { int t_ = (a); (a) = (b); (b) = t_; } while (0)
#define STR(x) #x                        /* stringize: STR(hi) -> "hi" */
#define JOIN(a, b) a##b                  /* paste tokens: JOIN(var, 1) -> var1 */
#define TYPE_NAME(x) _Generic((x), int: "int", double: "double", default: "other")

#ifndef INVENTORY_H         /* include guard (or #pragma once) */
#define INVENTORY_H
#endif

#if __STDC_VERSION__ >= 202311L
    /* C23 code */
#elifdef DEBUG              /* C23; older: #elif defined(DEBUG) */
#endif

#if __has_include(<threads.h>)          /* standard in C23 */
#endif

__FILE__  __LINE__  __func__  __DATE__  __STDC_VERSION__
assert(count > 0);                      /* <assert.h>; disabled by -DNDEBUG */
static_assert(sizeof(int) >= 4, "need 32-bit int");   /* compile time; keyword in C23 */

SQUARE(i++) evaluates i++ twice; prefer static inline functions when you can. Run gcc -E main.c to see the preprocessed source. See The Preprocessor, Macros, Conditional Compilation and Predefined Macros and assert.

Files

C
FILE *in = fopen("data.txt", "r");      /* "r" "w" "a" "r+" "w+" "a+", add "b" for binary */
if (in == NULL) {
    perror("data.txt");                 /* prints the reason, e.g. No such file or directory */
    return EXIT_FAILURE;
}
char line[256];
while (fgets(line, sizeof line, in) != NULL) { /* one line at a time */ }
if (ferror(in)) { /* a read error, not just end of file */ }
fclose(in);

FILE *out = fopen("out.bin", "wb");
fprintf(out, "%d\n", 42);               /* text */
fwrite(array, sizeof array[0], count, out);       /* binary: returns items written */
fread(array, sizeof array[0], count, in);         /* returns items read */
fseek(out, 0, SEEK_SET);  ftell(out);  rewind(out);
if (fclose(out) != 0) { /* buffered data may fail to write here */ }

/* stdin, stdout and stderr are FILE * too: fprintf(stderr, ...) */

Errors: functions report failure through their return value and set errno (<errno.h>); strerror(errno) gives the text. Read errno right after the failing call. See File Handling, Text Files, Binary Files and Error Handling.

Standard library at a glance

Header Highlights
<stdio.h> printf, fprintf, snprintf, puts, fgets, getchar, scanf, sscanf, fopen, fread, fwrite, perror
<stdlib.h> malloc, calloc, realloc, free, exit, atexit, strtol, strtod, qsort, bsearch, rand, abs, getenv
<string.h> strlen, strcmp, strchr, strstr, strtok, memcpy, memmove, memset
<ctype.h> isalpha, isdigit, isspace, toupper, tolower (pass unsigned char values)
<math.h> sqrt, pow, fabs, floor, ceil, round, fmod, sin, hypot, isnan (link with -lm)
<time.h> time, clock, difftime, localtime, gmtime, strftime
<stdint.h>, <inttypes.h> int32_t, uint64_t, INT64_MAX, PRId64
<limits.h>, <float.h> INT_MAX, CHAR_BIT, DBL_EPSILON, FLT_MAX
<stdbool.h>, <stddef.h> bool; size_t, ptrdiff_t, NULL, offsetof
<assert.h>, <errno.h> assert, static_assert; errno, ERANGE
<stdarg.h> va_list, va_start, va_arg, va_end
<stdckdint.h> (C23) ckd_add, ckd_sub, ckd_mul: overflow-checked arithmetic
<threads.h>, <stdatomic.h> (C11) thrd_create, mtx_lock; atomic_int, atomic_fetch_add
<pthread.h> (POSIX) pthread_create, pthread_join, pthread_mutex_lock

See The Math Library, Time and Date, Random Numbers, qsort and bsearch, stdlib.h utilities, Command-Line Arguments and Multithreading.

C23 in one block

C
bool ready = true;                  /* bool, true, false are keywords: no header needed */
int *p = nullptr;                   /* a real null pointer constant, type nullptr_t */
constexpr int limit = 1'000;        /* compile-time constant with a digit separator */
unsigned mask = 0b1010'0101;        /* binary literal */
typeof(limit) copy = limit;         /* typeof and typeof_unqual */
auto half = limit / 2.0;            /* type inference for object definitions */
[[nodiscard]] int must_check(void); /* attributes: also [[maybe_unused]], [[deprecated]] */
static_assert(sizeof(int) >= 4);    /* message is optional now */
int sum;
if (ckd_add(&sum, a, b)) { /* overflow */ }   /* <stdckdint.h> */
void f();                           /* now means (void): no parameters */

Not yet everywhere: <stdbit.h> (bit utilities), #embed (include a file's bytes) and %b in printf depend on how new your compiler and C library are. Check __STDC_VERSION__ >= 202311L and __has_include. See Modern C: C99 to C23.

Gotchas worth remembering

  • if (x = 5) assigns; compare with ==. -Wall warns.
  • -1 < 1u is false: the int converts to a huge unsigned value (Type Conversions).
  • char c = getchar(); breaks the EOF check; store the result in an int.
  • scanf("%d", &n) leaves the newline behind; reading lines with fgets avoids the mess.
  • sizeof on an array parameter gives the pointer size.
  • strncpy doesn't always terminate; snprintf does.
  • sizeof 'A' is sizeof(int) in C (it's 1 in C++), and sizeof "hi" is 3 because of the '\0'.
  • Signed overflow, out-of-bounds access, null dereference and i = i++ are undefined behavior: the compiler may assume they never happen.
  • Floating-point equality: compare fabs(a - b) < tolerance instead of a == b.
  • Every malloc needs exactly one free, and every fopen one fclose.
C Gotchas you can run

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with scanf or fgets), it gets the next line from this box.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which call reads a double correctly with scanf?

    For scanf, %f expects a float * and %lf a double *. printf is different, because float arguments are promoted to double, so %f and %lf mean the same thing there.
  2. 2. What does flags & MASK == 0 actually compute?

    The equality operators have higher precedence than bitwise AND. Write (flags & MASK) == 0 to test that no masked bit is set.
  3. 3. Given int a[5]; int *p = a;, which expression is NOT equal to a[2]?

    Unary * binds tighter than +, so *a + 2 is a[0] + 2. The other three all mean *(a + 2); even 2[a] is legal because indexing is defined as *(2 + a).
  4. 4. Why is new = realloc(old, size) assigned to a separate variable first?

    On failure realloc leaves the original block untouched. Keeping the old pointer lets you free it or keep using it.
  5. 5. What does printf("%d\n", -7 / 2); print?

    Since C99, integer division truncates toward zero, so -3.5 becomes -3. The matching remainder -7 % 2 is -1.

Summary

  • Types, formats and limits: use %zu for size_t, %lf only in scanf for doubles, <stdint.h> for exact widths, and <limits.h> instead of guessing sizes.
  • Read input with fgets and parse it with strtol/strtod/sscanf; build strings with snprintf.
  • Parenthesize mixed bitwise and comparison expressions; remember *p++ versus (*p)++.
  • Arrays decay to pointers when passed, so pass lengths explicitly; a[i] is *(a + i).
  • Pair every malloc with one free and every fopen with one fclose; check every return value.
  • Structs copy with =, use -> through pointers, and may contain padding.
  • C23 brings bool, nullptr, constexpr, typeof, auto, attributes and <stdckdint.h>; check support before relying on the newest library pieces.

Next: C Programs: 50 Classic Examples, a collection of runnable classics, from primes and palindromes to matrices and sorting, each linked to the lesson behind it.