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
strstris the wrong function for the L3 mess; you’re looking at the end of the string, so find that, save the character, and switch on it.elem_sizeis so bad. Soooooooo bad. First of all,casedoesn’t make statements, it’s a label.{}does fuck-all in this case. Second, you’re placing the labels at the wrong indentation in most styles—as in assembly language, the label is typically placed at the base indentation for the scope, socaseandswitchshould generally line up. This is especially important if thecasehappens to be in a subordinate statement. Third, thedefaultcase should be afor(;;) abort();or error return; 1 is not generally reasonable. And this function shouldn’t need to be a function, and it shouldn’t need to exist!#defines in publicconfig.h(int_treal_tcomplex_t), which if redefined improperly (which you permit readily) will bring the headers into conflict with the compiled library. This is why you define separate APIs for separate types; if you have to, use private xheaders and private/temporary macros to spløøt each version, given a type parameter and limit macro prefix.set_int_limitandset_real_limitare incorrect.int40_twill have the same size as anint64_t, just with several padding bytes. Size tells you nothing about range; you’d need the limit constants for that.int,long, orlong long;short, (nonstd.)short short, (nonstd.)short long,signed char,intXX_t,int_leastXX_t,int_fastXX_t,__int128/__int128_t,intptr_t, andptrdiff_taren’t handled; and you don’t really do anything to prevent unsigned types from being used—which may be perfectly reasonable—so you might be way off on those limits.*outwon’t be set.set_real_limit’s minimum is useless. You actually need theMINvalue most of the time.set_real_limitassumesINFINITYis a thing, without anything actually validating that IEEE 754 or something similar is in use. I think this bumps your minimum required language level to C11. Again, this is why you can’t just say “ISO C” and expect it to be meaningful, especially when it comes to math.breakondefaultcase inset_real_limitorset_complex_limit. Hypothetically optional, but a bad idea to omit, and in any case you’ve done so inconsistently.set_complex_limitdoesn't actually make sense; there is no (int-like) minimum or maximum (float-like minimum == 0), because min and max apply to 1-dimensional inputs, and complex numbers are ≥2D. There’s a maximum magnitude, there are corners of bounding rectangles, but there is no maximum complex value.+ 0.0 * I, and if the imaginary component is always zero for min and max, you’re just getting the real limit. Also, you don’t need to have calledset_real_limit(…, Min)unless you’re incase Min(have I told you I hate your enum names?), and you only needset_real_limit(…, Max)incase Max. So you’re just wasting effort and storage. Put areal_t tright after theswitch’s{, and get the limit in the specific case(s) that require it.get_limitis just begging for an aliasing violation.DGLshould union its function pointers, right? It’s a discriminated union? But then,DGL_newwithvoid *functionparameter would be a really bad idea. Function and object pointers should be treated as existing in their own universes. C will let you convert freely betweenvoid *andvoid (*)(…), but you’re not guaranteed to be able to round-trip per ISO 9899, and neither does it guarantee useful results from this conversion. You can safely convert between arbitrary function pointer types, unlike object pointers, but that’s it, and it has to be explicit for prototype functions. So a union is a moderately better option.logging.c, I again see a replicated#ifdef-#definefor something you’ve unconditionally defined elsewhere. If you expect it to be a parameter, offload it and don’t define it yourself; else, define it in one place, as privately as possible.isattycall. You cannot determine whether any stream is a tty using only the C library, and you cannot assume every tty supports ECMA-48 unless you’ve already detected something UNIXlike (whose tty customs tend to derive from the DEC VT100 hardware lineage).LOG_VERBOSITYis all-caps why? and it’s not thread-safe, which nothing notes. DittoLOG_MODE(shouldn’t exist) andLOG_FILE_PTR; these need to be atomicized somehow, either by wrapping in a mutex or by doing something fancy and atomic. Otherwise, you need to carefully document exactly when it is and isn’t safe to log or configure logging.Log_prefixis the wrong way to go about it. Put your enums into an xmacro that binds the prefix, and then you can just index into astatic const char *const[]. DittoLog_color. (—Which is extern-linkage for some reason.)localtimetrashes and relies upon static state. This interacts with threading also, so logging from more than one thread concurrently is not safe.fflushregardless at the end ofLog_log.fprintfandfflushactually succeed, and disable logging if they fail.Log_info_thresholdexists why? And it multiplies without an overflow check;%zurequires C99 and excludes older MSVCRT; and why is itprintfing, for fuck’s sake? Do you need to trash the primary output for the program every time the info threshold (whatever that’s used for) is set? If you want to do a size check like this, it’d beobject_size && count >= LOG_INFO_THRESHOLD / object_size, but even then I don’t see the point of making this an extern-linkage function.../in your header paths. If you want to useincludeas an include directory, use option-Ior theCPATH(most Unix) orC_INCLUDE_PATH(GNU, Clang) variable to add it to the include path, and then""and<>will both work. But your public and private includes should be separate, and your public includes need their own container directory so they’re not pissing up the public include namespace. Your code is not the only thing in the universe.-Dor-include, and defining it arbitrarily inside the library without even using<unistd.h>or checking for_POSIX_VERSIONis just weird. Either require POSIX.1 or don’t.<omp.h>only exists if_OPENMP-0 >=whatever its minimum value is, someYYYYMMLjobby like__STDC_VERSION__or_POSIX_VERSION. And it has to be specifically enabled for most compilers, so it’s not like you can just include it whenever.INITIALIZERis a marvelously mis-descriptive name, and an incredibly poor idea syntactically. Fortunately, I see you’re not actually using it.static PRNG_state prngmeans your PRNG is non-threadsafe, which is … a decision.==been a lower precedence than||. You only need parentheses if there’s some common, historical, or actual ambiguity (e.g.,&vs.|,||vs.|; or for things like!!(x = y)that shut the compiler up).staticfunctions canassert; otherwise, you need anifand some means of indicating the error àEINVAL._$foo_to_$barfunctions are, I believe, UB in quite a few cases (look at the rules for converting between floats and ints—there are potential UB cases in both directions IINM), but you have no idea which ones because you don’t actually know what types are involved. Also, leading identifiers with_is really not a good idea in general, especially after you’ve already included libc headers. It’s fine for macro parameters, it’s sometimes fine for struct fields or local variables, but otherwise it’s bad juju at best, undefined behavior at worst for things like_Foo.(cont’d)