ENGIMY.IO - CHEATSHEET
C × QUICK REFERENCE
REFERENCE vC11

C Quick Reference

Everything you need day‑to‑day – syntax, examples, and common pitfalls.

Data Types

Basic Types
  • int4 bytes (usually)
  • char1 byte
  • float4 bytes
  • double8 bytes
  • voidno value
  • short2 bytes
  • long4 or 8 bytes
  • long long8 bytes
Qualifiers
  • constread‑only variable
  • volatilemay change unexpectedly
  • signed / unsigned
  • staticretains value / file‑scope
  • externdefined elsewhere
  • registersuggest register storage

Common Type Sizes (check with sizeof())

// Typical sizes (may vary by system)
printf("%zu\n", sizeof(int));     // 4
printf("%zu\n", sizeof(char));    // 1
printf("%zu\n", sizeof(float));   // 4
printf("%zu\n", sizeof(double));  // 8
printf("%zu\n", sizeof(int*));    // 8 (64‑bit) / 4 (32‑bit)

Variables

// Declaration
int age = 25;
float pi = 3.14159f;
char grade = 'A';
char name[] = "Alice";
const double TAX_RATE = 0.08;

// Multiple declarations
int x = 0, y = 1, z = 2;

// Printing
printf("Age: %d, Name: %s\n", age, name);

// Format specifiers
// %d – int, %c – char, %s – string
// %f – float, %lf – double, %p – pointer
// %x – hex, %o – octal, %u – unsigned

Control Flow

if / else if / else

if (x > 0) {
    printf("positive\n");
} else if (x == 0) {
    printf("zero\n");
} else {
    printf("negative\n");
}

switch

switch (grade) {
    case 'A':
        printf("Excellent\n");
        break;
    case 'B':
        printf("Good\n");
        break;
    default:
        printf("Keep trying\n");
}

Loops

// for loop
for (int i = 0; i < 10; i++) {
    printf("%d ", i);
}

// while loop
int i = 0;
while (i < 10) {
    printf("%d ", i);
    i++;
}

// do‑while loop
int i = 0;
do {
    printf("%d ", i);
    i++;
} while (i < 10);

// break / continue
for (int i = 0; i < 20; i++) {
    if (i % 2 == 0) continue;   // skip evens
    if (i > 15) break;        // exit loop
    printf("%d ", i);
}

Functions

Declaration & Definition

// Prototype (before main)
int add(int a, int b);

// Definition
int add(int a, int b) {
    return a + b;
}

// Void function
void greet(char* name) {
    printf("Hello, %s!\n", name);
}

Function Pointers

// Declare a function pointer
int (*operation)(int, int);

operation = &add;
int result = operation(5, 3);  // returns 8

// Passing function as argument
int apply(int a, int b, int (*func)(int, int)) {
    return func(a, b);
}

Pointers

Basics

int value = 42;
int* ptr = &value;     // pointer to value

printf("value: %d\n", value);   // 42
printf("ptr: %p\n", ptr);        // address of value
printf("*ptr: %d\n", *ptr);      // 42 (dereference)

*ptr = 100;             // change value via pointer
printf("value: %d\n", value);   // 100

Pointer Arithmetic

int arr[] = {10, 20, 30, 40};
int* p = arr;           // points to arr[0]

printf("%d\n", *p);        // 10
printf("%d\n", *(p + 1));    // 20
printf("%d\n", *(p + 2));    // 30

// arr[i] is equivalent to *(arr + i)

Null Pointers

int* ptr = NULL;
if (ptr == NULL) {
    printf("Pointer is null\n");
}

Arrays

Declaration & Initialisation

// One‑dimensional
int arr[5] = {1, 2, 3, 4, 5};
int arr2[] = {1, 2, 3};   // size auto‑deduced (3)
int arr3[10] = {0};      // all elements zero

// Multi‑dimensional
int matrix[3][4] = {
    {1, 2, 3, 4},
    {5, 6, 7, 8},
    {9, 10, 11, 12}
};

// Accessing
int x = arr[2];          // 3
int y = matrix[1][2];    // 7

Strings (char arrays)

// String literal
char str1[] = "Hello";

// Null‑terminated char array
char str2[6] = {'H', 'e', 'l', 'l', 'o', '\0'};

// Common string functions (string.h)
strlen(str1);           // length (5)
strcpy(dest, src);      // copy
strcat(dest, src);      // concatenate
strcmp(str1, str2);     // compare (0 if equal)
strstr(haystack, needle); // find substring

Memory Management

// malloc – allocate memory
int* arr = (int*)malloc(10 * sizeof(int));
if (arr == NULL) {
    printf("Memory allocation failed\n");
    return 1;
}

// calloc – allocate + zero‑initialise
int* arr2 = (int*)calloc(10, sizeof(int));

// realloc – resize memory
arr = (int*)realloc(arr, 20 * sizeof(int));

// free – deallocate
free(arr);
arr = NULL;

File I/O

// Open file
FILE* fp = fopen("file.txt", "r");
if (fp == NULL) {
    perror("Error opening file");
    return 1;
}

// Read a character
int ch = fgetc(fp);
printf("%c", ch);

// Read a line
char buffer[256];
fgets(buffer, sizeof(buffer), fp);

// Read formatted
int num;
fscanf(fp, "%d", &num);

// Write to file
FILE* out = fopen("output.txt", "w");
fprintf(out, "Number: %d\n", num);
fclose(out);

// Close file
fclose(fp);

// Modes: r (read), w (write), a (append)
// r+ (read/write), w+ (read/write, truncate)
// a+ (read/append)

Preprocessor Directives

// Include headers
#include <stdio.h>      // system header
#include "myheader.h"  // local header

// Macros
#define PI 3.14159
#define SQUARE(x) ((x) * (x))

int area = SQUARE(5);   // expands to ((5) * (5))

// Conditional compilation
#ifdef DEBUG
    printf("Debug mode\n");
#endif

#ifndef HEADER_H
#define HEADER_H
// header guard
#endif

Common Standard Library Functions

stdio.h
  • printf() – formatted output
  • scanf() – formatted input
  • fopen() – open file
  • fclose() – close file
  • fgets() – read line
  • fprintf() – write to file
  • fscanf() – read from file
  • fgetc() / fputc()
stdlib.h
  • malloc() – allocate memory
  • calloc() – allocate + zero
  • free() – deallocate
  • realloc() – resize
  • atoi() – string → int
  • atof() – string → double
  • rand() / srand()
  • exit() – terminate
string.h
  • strlen() – length
  • strcpy() – copy
  • strcat() – concatenate
  • strcmp() – compare
  • strstr() – find substring
  • strchr() – find char
  • strtok() – tokenise
  • memcpy() – copy memory
  • memset() – set memory
math.h
  • sin() / cos() / tan()
  • sqrt() – square root
  • pow() – power
  • exp() – exponential
  • log() – natural log
  • ceil() / floor()
  • abs() – absolute value (stdlib.h)

Structs & Unions

// Struct definition
struct Person {
    char name[50];
    int age;
    float height;
};

// Create and use
struct Person person1;
strcpy(person1.name, "Alice");
person1.age = 25;
person1.height = 1.65;

// With typedef
typedef struct {
    char name[50];
    int age;
} Person;

Person p = {"Bob", 30};

// Pointers to structs
Person* ptr = &p;
printf("Name: %s\n", ptr->name);  // arrow operator

// Union (overlapping memory)
union Data {
    int i;
    float f;
    char str[20];
};

Compilation

Compile with gcc:

gcc program.c -o program       // compile
gcc program.c -o program -Wall  // with warnings
gcc program.c -o program -g     // with debug symbols
gcc program.c -o program -O2    // optimisation level 2
gcc -c program.c                // compile to object file
gcc program.o -o program        // link object file
./program                       // run

C Tips & Pitfalls

  • Always check for NULL after malloc() and fopen().
  • Free allocated memory – every malloc() should have a matching free().
  • Array bounds are not checked – accessing arr[10] on a 10‑element array is undefined behaviour.
  • Strings are null‑terminated – always allocate one extra char for '\0'.
  • Use sizeof() instead of hardcoding sizes.
  • Function prototypes – declare them before main() or use header files.
  • Prefer fgets() over gets()gets() is dangerous and removed in C11.
  • Use const to protect read‑only variables.
📌 Quick Reference
Check your C version: gcc --version
Compile with debug: gcc -g program.c -o program
Run with valgrind (memory check): valgrind ./program
See assembly output: gcc -S program.c
← Back to All Cheatsheets