From b49f11657dc95dca8ebbfa24d1fda0f6ea07fa7d Mon Sep 17 00:00:00 2001 From: liquidev Date: Tue, 12 Nov 2024 14:52:19 +0100 Subject: [PATCH] add a note on prefix matches with C strings --- content/programming.tree | 4 ++++ .../programming/blog/cstring-starts-with.tree | 17 +++++++++++++++++ 2 files changed, 21 insertions(+) create mode 100644 content/programming/blog/cstring-starts-with.tree diff --git a/content/programming.tree b/content/programming.tree index 6dd3b55..948e67a 100644 --- a/content/programming.tree +++ b/content/programming.tree @@ -13,6 +13,10 @@ id = "01J4J4PAXRWZDP9PAZNGCQ9S3D" + [featured]{.badge .blue} :page: haku - writing a little programming language for fun + % content.link = "programming/blog/cstring-starts-with" + id = "01JCGAM56KS2C6D4XZ1MRATXH4" + + :page: prefix matches with C strings + % content.link = "programming/blog/buildsome" id = "01J7BYKQHZKYQ969T3PH3V8HF1" + :page: not quite buildless diff --git a/content/programming/blog/cstring-starts-with.tree b/content/programming/blog/cstring-starts-with.tree new file mode 100644 index 0000000..1965bee --- /dev/null +++ b/content/programming/blog/cstring-starts-with.tree @@ -0,0 +1,17 @@ +%% title = "prefix matches with C strings" + +% id = "01JCGAM55352EF247HZ358BAJ8" +- one thing I realised while reading some code at work that worked with C strings: it's surprising how easy it is to match a prefix on a C string. + +```c +if (s != NULL + && s[0] == 'h' + && s[1] == 'u' + && s[2] == 'g') +{ + // ... +} +``` + +% id = "01JCGAM5537WYE3GEN6WGX8WD0" +- this works because of the NUL terminator---if it appears at any point in the string, the `s[i] == c` comparison will return `false`, thus breaking the `&&` chain---so indices always stay in-bounds!