add a note on prefix matches with C strings

This commit is contained in:
りき萌 2024-11-12 14:52:19 +01:00
parent 0b0c0a4de4
commit b49f11657d
2 changed files with 21 additions and 0 deletions

View file

@ -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!