C: reference
The language operating systems are written in: types, pointers, memory, structures and files.
Program structure
Minimal program
A program starts at main. #include pulls in a header with declarations, printf prints formatted text, and return 0 tells the system it succeeded.
#include <stdio.h>
int main(void) {
printf("Hello, world!\n");
return 0;
}Compiling and running
C compiles to machine code. The -Wall -Wextra flags enable useful warnings, and -std=c11 fixes the language standard.
gcc -std=c11 -Wall -Wextra main.c -o main ./main
Variables and types
Basic types
The type is given at declaration. A local variable without an initializer holds random garbage, so always set an initial value.
int age = 16; double price = 24.5; char letter = 'A'; unsigned int count = 3u; const double PI = 3.14159;
Fixed-width types
The stdint.h header provides types of guaranteed size, and stdbool.h adds bool, true and false.
#include <stdint.h> #include <stdbool.h> int32_t a = 100000; uint8_t byte = 255; bool ok = true;
Conversion
Integer division drops the fractional part. For reliable string parsing use strtol and strtod, which report errors.
int n = (int)3.9; // 3
double d = 7 / 2.0; // 3.5
double e = 7 / 2; // 3.0: integer division
#include <stdlib.h>
int x = atoi("12");
double y = strtod("3.5", NULL);Input and output
printf
Specifiers: %d integer, %u unsigned, %f floating-point, %c character, %s string, %zu size, %p address.
printf("%d %5.2f %c %s\n", 42, 3.14159, 'x', "string");
printf("%zu bytes\n", sizeof(int));scanf and fgets
scanf returns the number of values read: always check it. For strings fgets is safer, as it stays within the buffer.
int n;
if (scanf("%d", &n) == 1) printf("%d\n", n * 2);
char line[64];
if (fgets(line, sizeof line, stdin)) printf("%s", line);Conditions and loops
if, else, switch
End every switch branch with break, otherwise execution “falls through” into the next one.
if (age < 12) {
puts("child");
} else if (age < 18) {
puts("teenager");
} else {
puts("adult");
}
switch (day) {
case 1: puts("Mon"); break;
default: puts("other");
}Loops
for suits a known number of steps, while checks the condition before the body, and do … while runs the body at least once.
for (int i = 0; i < 5; i++) printf("%d ", i);
int n = 3;
while (n > 0) n--;
do { n++; } while (n < 3);Functions
Declaration and call
A prototype tells the compiler about a function before its definition. In C arguments are passed by value: the function works with a copy.
int square(int x);
int main(void) {
printf("%d\n", square(7));
return 0;
}
int square(int x) {
return x * x;
}Output parameters
To let a function change or return several values, pass it pointers to the variables.
void min_max(const int *a, int n, int *lo, int *hi) {
*lo = *hi = a[0];
for (int i = 1; i < n; i++) {
if (a[i] < *lo) *lo = a[i];
if (a[i] > *hi) *hi = a[i];
}
}Arrays and strings
Array
An array has a fixed size and no bounds checking: going out of bounds is undefined behavior. When passing an array to a function, pass its length too.
int a[5] = {1, 2, 3};
size_t n = sizeof a / sizeof a[0];
for (size_t i = 0; i < n; i++) printf("%d ", a[i]);Strings
A C string is a char array ending with a zero byte \0. Track the buffer size yourself and copy carefully.
#include <string.h>
char s[16] = "Hello";
size_t len = strlen(s);
strncpy(s, "ok", sizeof s - 1);
int same = strcmp("a", "b") == 0;Pointers and memory
Pointer
&x is the address of a variable, *p is the value at an address. A NULL pointer means “nowhere”.
int x = 10;
int *p = &x;
*p = 20;
printf("%d %p\n", x, (void *)p);malloc and free
Every malloc needs exactly one free. Check the result for NULL and never use memory after free.
#include <stdlib.h> int *a = malloc(5 * sizeof *a); if (a == NULL) return 1; for (int i = 0; i < 5; i++) a[i] = i * i; free(a); a = NULL;
Structures
struct and typedef
struct groups fields of different types. Fields are accessed through a pointer with the arrow ->.
typedef struct {
char name[20];
int age;
} Person;
Person p = { "Alex", 17 };
Person *q = &p;
printf("%s %d\n", q->name, q->age);enum
enum gives named integer constants: handier and safer than “magic numbers”.
enum Color { RED, GREEN, BLUE };
enum Color c = GREEN;Files
Reading and writing
Always check the result of fopen and close the file with fclose.
FILE *f = fopen("data.txt", "r");
if (f == NULL) { perror("fopen"); return 1; }
char line[128];
while (fgets(line, sizeof line, f)) fputs(line, stdout);
fclose(f);Preprocessor
Macros and conditional compilation
A macro is substituted as text before compilation. Wrap macro parameters in parentheses and don't pass expressions with side effects.
#define MAX 100
#define SQUARE(x) ((x) * (x))
#ifdef DEBUG
puts("debugging");
#endifHeader guard
A header guard stops the same thing from being declared twice.
#ifndef SHAPES_H #define SHAPES_H double area(double w, double h); #endif
Learn C with practice
- 110 lessons, 80 of them base
- Tasks with in-browser code checking
- Free, nothing to install