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. 0 means it finished fine.
int twice(int n);A prototype lets code above the function's body call it.
1 more: comments
// 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.
scanf("%d", &level);Reads a number into level. & gives its address.
fgets(line, sizeof line, stdin);Reads a whole line safely, spaces included.
1 more: widths and decimals
printf("%.2f %5d %-8s\n", price, score, tag);2 decimal places, right-aligned in 5, left-aligned in 8.
Types
char c = 'A'; int n = 42; double d = 3.5;1, 4 and 8 bytes here. long is 4, long long is 8.
7 / 2 7 / 2.0 (double)total / count3, then 3.5. Make one side a double to keep the fraction.
2 more: sizeof, unsigned
sizeof(int) sizeof scoresSize in bytes, of a type or of a variable.
unsigned int u = 4000000000u;No negatives, twice the top range. Careful mixing with signed.
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: most array loops.
while (lives > 0) { ... }Repeats while true. Make sure something changes it.
1 more: break and continue
break; continue;Leave the loop now, or skip to its next round.
Arrays
int scores[5] = {12, 7, 30, 18, 4};Five ints, 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, so pass the length too.
1 more: 2D arrays
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) == 0True when they match. a == b compares addresses.
1 more: building strings safely
snprintf(buf, sizeof buf, "%s:%d", name, score);Builds a string, 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 your variable.
1 more: pointer arithmetic
p + 1 p[2] *(p + 2)p + 1 moves one item. p[2] is the same as *(p + 2).
Locked
The heap
Code 4 rows
Structs and pointers
Code 4 rows
Files
Code 4 rows