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/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.