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

2

u/max123246 Sep 13 '26 edited Sep 13 '26

They loved within the for loop expression or while loop expression to put gets so that you have a side effect of the gets and you use the return as a condition to the loop

As an example: https://github.com/caisah/K-and-R-exercises-and-examples/blob/master/01.05.3-line_counting/ex-count_lines.c#L9

And another example: https://github.com/caisah/K-and-R-exercises-and-examples/blob/913d6427cd397aeaf649e839ceb77ef5d5e75a61/04.02-functions_returning_non_integers/ex-primitive_calculator.c#L24


    for (val = 0.0; isdigit(s[i]); i++)
        val = val * 10.0 + (s[i] - '0');

They also declared variables all upfront without an initial value

It's not bad patterns per se but no one would write code like it today. It definitely makes code harder to understand as a beginner

1

u/musbur Sep 14 '26

What's wrong with the number parsing snippet ("wrong" in the sense of promising more than it can deliver)?

1

u/SeriousPlankton2000 Sep 15 '26

Declaring variables without a dummy value is a good thing to be warned about accessing undefined values. If you do have int foo = 0xdeadbeef, you can get 0xdeadbeef in production; if you have int foo, you get a warning or an error while compiling if you e.g. miss setting it in a case branch of a switch statement.

I'd agree that it's better to declare and set a variable later in a function as soon as you can set its value - provided that there is a linear path that allows doing so. (I like to have the full context of a variable on screen - if possible.)

2

u/max123246 Sep 15 '26

By default compilers will emit a warning and let your uninitialized variable invoke undefined behavior. Yes, you should have warnings as errors but it's still not great when basically all variables could have a sensible initial value

1

u/SeriousPlankton2000 Sep 16 '26

What is the sensible init value that will be different from a good value?

Also is it sensible to add dummy writes to the stack?

2

u/max123246 Sep 16 '26

If you're adding in a loop, 0, if you're multiplying in a loop, 1, if you're branching and setting values, then the value of one of the branches

Your compiler optimizes away dummy writes if it's truly unneeded. Compilers are really good at constant folding and removing unused values in particular. They're less good at loop hoisting or loop auto vectorization