welcome to
evildojo


Howto C

Based off of https://matt.sh/howto-c


Table of Contents


Makefiles

gcc/clang flags:

-std=c11 or -std=c99
-O2 or -O3 or -Os
-Wall 
-Wextra 
-Wpedantic 
-Werror -Wshadow
-Wstrict-overflow
-fno-strict-aliasing
-Wno-missing-field-initializers
-march=native

Types

#include <stdint.h>

// int8_t
// int16_t
// int32_t
// int64_t
// uint8_t
// uint16_t
// uint32_t
// uint64_t
// float
// double

// int_fast8_t
// int_fast16_t
// int_fast32_t
// int_fast64_t
// uint_fast8_t
// uint_fast16_t
// uint_fast32_t
// uint_fast64_t

// int_least8_t
// int_least16_t
// int_least32_t
// int_least64_t
// uint_least8_t
// uint_least16_t
// uint_least32_t
// uint_least64_t

// ptrdiff_t
// uintptr_t
// intptr_t

// intmax_t
// uintmax_t

// size_t
// ssize_t

Printing Types

size_t:            %zu
ssize_t:           %zd
ptrdiff_t:         %td
raw pointer value: %p
int64_t:           "%" PRId64
uint64_t:          "%" PRIu64
intptr_t:          "%" PRIdPTR
uintptr_t:         "%" PRIuPTR
intmax_t:          "%" PRIdMAX
uintmax_t:         "%" PRIuMAX

// example
printf("Test: %" PRIdPTR "\n\n", someIntPtr);

Declaring Vars

void test(uint8_t input) {
    if (input < 3) {
        return;
    }

    uint32_t b = input; // encouraged
}

Inline Counters

for (uint32_t i = 0; i < 10; i++)

Pragma Once

You no longer need include guards.

#pragma once

Static-init of auto-alloc'd arrays

uint32_t nums[32] = {0};

Static-init of auto-alloc'd structs

struct thing {
    uint64_t index;
    uint32_t counter;
}; 

struct thing localThing = {0};

For zeroing structs:

static const struct thing localThingNull = {0};

struct thing localThing = {.counter = 3};

localThing = localThingNull;

Variable-length arrays

uintmax_t arrayLen = strtoumax(argv[1], NULL, 10);
void *array[arrayLen];

Parameter Types

void processAddBytesOverflow(void *input, uint32_t len) {
    uint8_t *bytes = input;

    for (uint32_t i = 0; i < len; i++) {
        bytes[0] += bytes[i];
    }
}

Never Use malloc

calloc(objectCount, sizePerObject);
calloc(1, sizeOfObject);