Skip to content

Instantly share code, notes, and snippets.

@aprell
aprell / gotcha.sh
Created June 5, 2022 14:43
Be wary of arithmetic expressions when using `set -e`
#!/usr/bin/env bash
set -e
i=0
while [ $i -lt 3 ]; do
r=$((RANDOM % 10))
if [ $r -lt 3 ]; then
((i++))
@aprell
aprell / linearized_subscripts.c
Created January 17, 2022 17:17
Linearization of array subscripts
#include <stdio.h>
void standard(int A, int B, int C, int array[A][B][C]) {
for (int i = 0; i < A; i++) {
for (int j = 0; j < B; j++) {
for (int k = 0; k < C; k++) {
printf("%d\n", array[i][j][k]);
}
}
}
@aprell
aprell / static_assert.c
Created January 17, 2022 13:09
One of many ways to do compile-time assertions in C
#define STATIC_ASSERT(cond) ((void)sizeof(char[1 - 2 * !(cond)]))
struct S {
int x, y;
short z;
};
int main(void) {
STATIC_ASSERT(1 + 2 == 3);
STATIC_ASSERT(sizeof(float) <= sizeof(double));
@aprell
aprell / override.mk
Last active November 4, 2021 15:51
Overriding Makefile variables
test1: CFLAGS ?= -Wall -Wextra
test2: CFLAGS += -Wall -Wextra
test3: override CFLAGS += -Wall -Wextra
test4: override CFLAGS := -Wall -Wextra $(CFLAGS)
test1 test2 test3 test4:
@echo "$@: $(CFLAGS)"
@aprell
aprell / build.patch
Created February 19, 2021 14:28
Using https://github.com/sparverius/ats-acc under WSL 1 (Ubuntu 20.04 LTS)
diff --git a/DATS/Makefile b/DATS/Makefile
index ef0418e..6df16b0 100644
--- a/DATS/Makefile
+++ b/DATS/Makefile
@@ -7,12 +7,9 @@ MAKEFLAGS += --silent
######
-PATSCC=\
-$(PATSHOME)/bin/patscc
@aprell
aprell / value_numbering.ml
Last active November 1, 2020 19:15
Hash-based value numbering to eliminate redundant expressions
type stmts = stmt ref list
and stmt = Assign of var * expr
and expr =
| Int of int
| Val of var
| Binop of expr * expr (* e1 + e2 *)
and var = string
// https://rain-1.github.io/why/why.html
// https://github.com/rain-1/makes/tree/master/previous-version/makes.c
//
// Example usage:
// makes foo foo.c foo.h && gcc -Wall -Wextra -o foo foo.c
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
@aprell
aprell / gotcha.lua
Last active October 7, 2019 13:14
Another Lua gotcha
function f()
return 1, 2, 3
end
print(f()) -- 1 2 3
print(f(), 4) -- 1 4
print(4, f()) -- 4 1 2 3
@aprell
aprell / repeat.sh
Created September 4, 2019 13:19
Repeat a command until it fails with a non-zero exit code
#!/usr/bin/env bash
# ShellChecked with no issues detected
#
# Example usage for debugging a sporadically failing program:
# repeat.sh -- gdb --eval-command=run --eval-command=quit --args ./a.out
while [[ $1 != "--" ]]; do
n=$1
shift
done
@aprell
aprell / task.c
Created August 27, 2019 13:13
Yet another task macro
// CFLAGS="-Wall -Wextra"
#include <assert.h>
#include <stdbool.h>
#include <stdio.h>
#include <stdlib.h>
typedef struct task {
void (*func)(void *);
void *args;
struct task *next;