r/C_Programming • • Sep 12 '26

Question What C function would you delete and rewrite first, and why?

For me it's fnmatch - mostly because it's 40 year's old and smell's funny.

95 Upvotes

238 comments sorted by

View all comments

Show parent comment

3

u/sthlmtrdr Sep 12 '26

It's trivial to implement your own strings and string functions.

5

u/Gastredner Sep 12 '26

Only as long as you only care about ASCII.

3

u/honkai-yuri-fan Sep 12 '26

50% of the time character encoding barely matters, there are very few reasons to actually know how many visible characters are in a string

3

u/Gastredner Sep 12 '26

True enough, though the second you need to do sorting, you're screwed.

Edit: thinking about it, if you're dealing with Unicode, normalisation might even make seemingly simple operations a problem. After all, two visibly identical strings might have two (or possibly more?) different representations.

3

u/penguin359 Sep 12 '26

That doesn't help with string literals.

1

u/mccurtjs Sep 12 '26

It's easy enough to make a macro that constructs a slice out of a literal. my_print(S("Hello World")), for example.

1

u/flatfinger Sep 14 '26

There's no standard way of passing a pointer to e.g. a static-const length-prefixed string without having to create a named object for it--something that can't be done within the context of a macro.

1

u/mccurtjs Sep 17 '26

What do you mean by standard? I guess it depends on what target platforms you're asking for, but this has worked for me just fine:

#define S(C_STR) ((slice_t) { .begin = (C_STR), .length = sizeof(C_STR) - 1})

The compilers I've been using it on are gcc, clang, and msvc. The only issue between them is that msvc doesn't like the type being included when declaring a named global variable, so I have another one that's just the part in braces which works on all three.

I'm curious what situations this doesn't work in!

1

u/flatfinger Sep 21 '26

That code will, by specification, generate a new string object every time it is called. If invoked within a subroutine that is called recursively, the address of the object will be different at each level of nesting.

By contrast, if the construct had been written with a static const object, there would just be one copy of the string which could be kept in ROM, and at runtime code would simply pass its address.

2

u/mccurtjs Sep 12 '26

It's a fun side project, but it is kind of annoying if you're using any other library because almost any interop is going to require copying and null-terminating the string. If the standard library had been built using slices, all derivative libraries would have followed suit by convention and this wouldn't be an issue.