r/cprogramming • u/No_Entertainer_6928 • Aug 30 '26
Math library code review
I am relatively new to C so I try to improve my skills by making a math library. The biggest challenge was making generic containers for matrices and vectors, as I was kind of new to void pointer magic. I think I have polished the most glaring issues in the code but do any of you have suggestions for what I could be doing better in my approach to C? Github for reference:
5
Upvotes
View all comments
Show parent comment
2
u/nerd5code Aug 30 '26
_to_$foo_workersnotconst?void (*const name[LEN])($PARAMS)is the syntax. Also, you don’t even check that you’ve gotten a nonnull index from it when you execute through it. This is just so much extra indirection and abstraction for something that ought to be high-performance and direct. And then, you still require actual, separate functions in the backend, you’re just blocking the developer-user from accessing them, and making life much more difficult for the optimizer and CPU brpred in the process. Why?? Is there a reason for this? Is it just some obscene Python urge, where you really want to make sure everything runs at the same, lame speed as the interpreter? Because if so, definitely add more global state that’s locked exclusively at every API call.return MATRIX_SUCCESSstatements in_prepare_datatype? Wouldn’t it be better, perhaps, to gather all the information about each data type into a single,static const struct $something[], so you don’t have to scatter things around throughout countlessswitches and arrays?_prepare_datatype? You should already know that the arguments are valid, and thenassertabout that (default: assert(!*"invalid 'dt' field in B parameter"); for(;;) abort();)._elem_sizefunction in matrix.c that only acts onlong,double, andcomplex doublefor some reason, which is thus incompatible withelem_sizefrom config.c. Swell. What a good idea. Also, please stop with the overbracedswitches. Seriously, you need to learn the syntax before you attempt useful libraries. This all reeks of discomfort/unfamiliarity with basic aspects of the language.mibi_byte_sizeadouble? You’ve already breezed past the C11 assumption and you requiresnprintf, so you can just usesize_twithzmodifier, right? And you’ve already checked thatm * nwon’t overflow, right? —Oh wait, no you haven’t, so you’re just throwing numbers around. And you shouldn’t be logging here anyway.posix_memalign. So, you haven’t checked for POSIX.1 yet (you have to detect, then#include <unistd.h>, and then test_POSIX_VERSION-0 >= 200112L), C11 (which you’ve assumed) gives youaligned_alloc, but MSVC gives you_alloc_alignedand_free_alignedonly, and older Unix only gives you things likememalignormmap. And I don’t get why you’re aligning in the first place; here again, if the developer-user wants cache line alignment, they can actually detect the cache line (32 ain’t it, in all likelihood) and allocate their own damn structure using the facilities actually present on the target platform. Your math library does not need to allocate memory like this.Matrix’s memory was allocated? …Kind of, only in one place. You log (inappropriately) and return an “empty” matrix, then insufficiently many things actually check for it. It’s an overcomplicated approach. And … I’m not checking the rest of this file. It’s a damned mess. Just everything thrown everywhere, bizarre decisions about macro usage, no fun.0x94D049BB133111EBULL. Uh huh. And why are you usingsize_tfor the context, when the data types you’re working with need have nothing to do with its value range? Ifint_t⇒long longand you’re targeting ILP32, then you can’t generate the full range ofint_tvalues from your PRNG. And then, if you’re working withdoubles, you’ve got both an exponent and mantissa to reach, give or take transcendentals and subnormals.=s just anywhere? Either indent consistently or don’t. I suggest not, because it makes a mess.constvery inconsistently on locals. Either don’t or do, but splitting the difference doesn't inspire confidence. Also, in some cases you don’t need the variable at all; if you’re only using the value once and it’s obvious what it is, capturing it asxdoesn't add anything, and in unoptimized builds it’ll do an extra memory hit;registerwould fix that and be more in line with intent. (Ignore people who tell you it does nothing. It does nothing in C++, prior to its removal from the language. It does something in C, it just isn’t required to have a noticeable effect.)for(;;)s in yourPRNG_State_*functions are bad ideas; nothing prevents them from looping indefinitely.<alloca.h>is never something a library should rely on if you want it to be considered portable. Nothing about it is portable. The header isn’t, the function or “function” isn’t, its behavior and required placement isn’t, its interaction with inlining isn’t, etc. A pairedmalloc-freewhere the compiler can see both and knows both will be called is just fine; often it’ll be able to optimize to VLAs, if that’s appropriate.PARALLEL_THRESHOLDis defined in multiple places, and its default value in vector.c is different than the other definition._parallel_conditionis such a bad name. What is the function doing? What is the condition? Also,(size_t)(dim - lower) <= upperis how you do a range check, and you don’t need the variables that way. Not that you should be consulting non-conststaticstate like this in the first place.p == NULLis just!pin C, as isx == 0. Only for floats or enums would I explicitly use== 0.0(rarely) or== ZERO_ENUM(if there’s no obvious Boolean correspondence for the enum values).#pragma ompanything needs to be paired with_OPENMPdetection. There’s nothing actually constraining pragmas without it; ideally, the compiler does nothing with a pragma it doesn’t recognize, but#pragma ompis only constrained iff OpenMP is actually supported and active for the build, so it could do anything if not. It’s likely to raise warnings if not, in any event. Also#pragma omp simdrequires like … OpenMP 3 or 4 I wanna say? Not sure offhand, but it needs to be detected. Also, most compilers can vectorize a short loop like this without your assistance, and the reason this sort of thing ought to be as inlined as possible is so that, when somebody’s repeating as vector operation across multiple rows/columns of a matrix, the compiler can potentially vectorize the entire thing together, which might enable it to skip lead-in/-out etc.ACCESS_VOID, and I hate how much you’re leaning on it.qsortis arguably better for in-place sorts, though its lack of funarg fucks its usefulness up quite a bit.)#pragma omp simding the macros that don’t need to exist. What made you decide that any of that was a good idea? An inlinedforloop would be fine 99% of the time; you don’t/shouldn’t needSUB, and you certainly shouldn’t assume#pragma omp simdcan be applied to it, because it should probably be in ado/while(0)in the first place. You can potentially embed_Pragma("omp simd")(C99 non-MS/ICL, GNU 3, Clang, ICC/ECC 8+, most C99-capable compilers) or__pragma(omp simd)(defined _MSC_VER || (defined __clang__ && defined __pragma) || defined __INTEL_COMPILER_BUILD_DATE) within the macro, but again, you shouldn’t need to.Every single operation you perform on a signed integral type or floating-point type needs to be bounds-checked, because overflow is undefined behavior. Even
_negate_intcan overflow (atINT_MIN, for two’s-complement or asymmetric mappings to unsigned value) (which is still distinct from bytewise representation). If you rely on f.p. transcendentals, you need to detect them (__STDC_IEC_559__,__STDC_IEC_60559_*__, GNU__GCC_IEC_559, GNU__GCC_IEC_559_COMPLEX, GNU__FOO_IS_IEC_60559__), and you often have to check complex and real f.p. separately.Also, you do know that GNU dialect permits
_Complexto be applied to things other than floating-point types? It’s UB or ISB in C99, but it’d be somewhat reasonable for somebody to#define complex_t _Complex long _Fractjust to fuck with you.OK, I'm not doing
tests.Sooooooo many of these functions you repeat for every blasted data type could just have been macros or xheaders, which would divide the amount of code you need by 3, and completely obviate the need for the
_ts that oughtn’t be.And the important aspects of the math stuff (e.g., dealing with corner cases) just aren’t here.