Brainlag
  1. Library
  2. Cheatsheets
  3. C

C cheatsheet

The C you reach for most, from printf and types to arrays, strings, pointers, the heap, structs and files, one short line at a time.

Program shape

#include <stdio.h>

int main(void) {
    return 0;
}

Every program starts in main. Returning 0 means it finished fine.

int twice(int n);

A prototype: lets code above the function's body call it.

// one line
/* several lines */

Comments. The compiler skips them.

Printing and reading

printf("%s has %d hp\n", name, hp);

%d int, %s string, %c char, %f double, %p pointer, \n new line.

printf("%.2f %5d %-8s\n", price, score, tag);

2 decimal places, right-aligned in 5, left-aligned in 8.

scanf("%d", &level);

Reads a number into level. It needs the address, hence the &.

fgets(line, sizeof line, stdin);

Reads a whole line, spaces included, without overflowing line.

Types

char c = 'A';  int n = 42;  double d = 3.5;

1, 4 and 8 bytes on this site. long is 4 here, long long is 8.

sizeof(int)   sizeof scores

Size in bytes, of a type or of a variable.

7 / 2       7 / 2.0       (double)total / count

3, then 3.5. Make one side a double to keep the fraction.

unsigned int u = 4000000000u;

No negatives, twice the top range. Mixing signed and unsigned surprises people.

Control flow

if (hp <= 0) { ... } else if (hp < 20) { ... } else { ... }

Any non-zero value counts as true; 0 is false.

for (int i = 0; i < n; i++) { ... }

Count from 0 while below n: the shape of most array loops.

while (lives > 0) { ... }

Repeats while the condition holds. Make sure something changes it.

break;   continue;

Leave the loop now, or skip to its next round.

Arrays

int scores[5] = {12, 7, 30, 18, 4};

Five ints side by side. Indexes 0 to 4. The size never changes.

int n = sizeof scores / sizeof scores[0];

The length, but only where the array was declared.

int best(const int *a, int n);

A function gets a pointer to the first item, so pass the length too.

int grid[3][4];   grid[row][col] = 1;

A 2D array: 3 rows of 4.

Strings

char tag[] = "Neon";

5 chars: N, e, o, n and the 0 terminator.

#include <string.h>
strlen(tag)

Counts chars before the 0: 4. sizeof tag is 5.

strcmp(a, b) == 0

True when the strings match. a == b compares addresses, not text.

snprintf(buf, sizeof buf, "%s:%d", name, score);

Builds a string safely, never writing past buf.

Pointers

int *p = &hp;

p holds the address of hp.

*p = 70;

Writes 70 into hp, through the pointer.

void heal(int *hp, int amount) { *hp += amount; }
heal(&player_hp, 10);

Pass an address so a function can change the caller's variable.

p + 1   p[2]   *(p + 2)

p + 1 moves one item (4 bytes for int). p[2] is the same as *(p + 2).

The heap

Premium 4 rows

Structs and pointers

Premium 4 rows

Files

Premium 4 rows

Premium The three marked sections come with Premium. See Premium