r/cprogramming • • 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:

https://github.com/VatoQ/hoema-prak-clang

5 Upvotes

8 comments sorted by

View all comments

Show parent comment

2

u/nerd5code Aug 30 '26
  • Why is _to_$foo_workers not const? 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.
  • Do you need three completely separate return MATRIX_SUCCESS statements 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 countless switches and arrays?
  • Why are you logging errors from _prepare_datatype? You should already know that the arguments are valid, and then assert about that (default: assert(!*"invalid 'dt' field in B parameter"); for(;;) abort();).
  • Oh and now there’s a completely separate _elem_size function in matrix.c that only acts on long, double, and complex double for some reason, which is thus incompatible with elem_size from config.c. Swell. What a good idea. Also, please stop with the overbraced switches. Seriously, you need to learn the syntax before you attempt useful libraries. This all reeks of discomfort/unfamiliarity with basic aspects of the language.
  • matrix.c:235–248: holy fuck what is this, just … any of it? Why is mibi_byte_size a double? You’ve already breezed past the C11 assumption and you require snprintf, so you can just use size_t with z modifier, right? And you’ve already checked that m * n won’t overflow, right? —Oh wait, no you haven’t, so you’re just throwing numbers around. And you shouldn’t be logging here anyway.
  • Ohhhhhh you’re using 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 you aligned_alloc, but MSVC gives you _alloc_aligned and _free_aligned only, and older Unix only gives you things like memalign or mmap. 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.
  • Did somebody tell you to use underscore-prefixing?? Slap them about the face several times, and ignore anything else they tell you.
  • OK, I’m not trawling through all your matrix code. It's generally bonkers, not into it, not going to perform well, no idea why you’re logging in the weirdest possible places.
  • Are you actually checking that the 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.
  • So you’ll define arbitrary constants in public headers where they aren’t needed, but you won’t define the shift constants you repeat throughout prng.c, or 0x94D049BB133111EBULL. Uh huh. And why are you using size_t for the context, when the data types you’re working with need have nothing to do with its value range? If int_t ⇒ long long and you’re targeting ILP32, then you can’t generate the full range of int_t values from your PRNG. And then, if you’re working with doubles, you’ve got both an exponent and mantissa to reach, give or take transcendentals and subnormals.
  • Why are you repeating your XORshift-multiply blocks?
  • Why are you placing =s just anywhere? Either indent consistently or don’t. I suggest not, because it makes a mess.
  • You’re using const very 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 as x doesn't add anything, and in unoptimized builds it’ll do an extra memory hit; register would 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.)
  • Your for(;;)s in your PRNG_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 paired malloc-free where 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.
  • Here again, PARALLEL_THRESHOLD is defined in multiple places, and its default value in vector.c is different than the other definition.
  • _parallel_condition is such a bad name. What is the function doing? What is the condition? Also, (size_t)(dim - lower) <= upper is how you do a range check, and you don’t need the variables that way. Not that you should be consulting non-const static state like this in the first place.
  • p == NULL is just !p in C, as is x == 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).
  • The potential for shape mismatch is something that should be hoisted so it’s more obvious to the developer, because this just shoves all the important stuff behind a mess of functions that then forward into a bigger mess of functions. Also it’d be a programmer error, not a warning.
  • #pragma omp anything needs to be paired with _OPENMP detection. There’s nothing actually constraining pragmas without it; ideally, the compiler does nothing with a pragma it doesn’t recognize, but #pragma omp is 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 simd requires 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.
  • I still hate ACCESS_VOID, and I hate how much you’re leaning on it.
  • If you ever extend your data type enum, you’re so fucked.
  • Yyyyyyyyyyyyeah if you’re going to do a sort, you need to document the algorithm. But you shouldn’t, and you aren’t sorting as quickly as you could be, which is why you should leave it to the devel-user. (Also qsort is arguably better for in-place sorts, though its lack of funarg fucks its usefulness up quite a bit.)
  • Oh god you’re #pragma omp simding the macros that don’t need to exist. What made you decide that any of that was a good idea? An inlined for loop would be fine 99% of the time; you don’t/shouldn’t need SUB, and you certainly shouldn’t assume #pragma omp simd can be applied to it, because it should probably be in a do/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_int can overflow (at INT_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 _Complex to 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 _Fract just 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.