r/C_Programming • u/non-existing-person • Oct 11 '26
Discussion Share your favorite, generic macro you use constantly
Macros can be bad. But they can also be very good. What are the macros you guys use very heavily in your own projects? I plan to steal them, just so you now :D
Rules:
- don't write definition and "what" comment, if we can't figure out what macro does by it's usage, it's not a good macro
- you can (and probably should) provide example usage
- you can say why you like it
I'll start
int foo(int *arg, enum e e) {
VALIDATE(-1, EINVAL, arg, "arg cannot be null");
VALIDATE(-1, EINVAL, e < ENUM_MAX);
...
/* normal function execution */I also have ASSERT that is almost the same. Why? Saves A LOT of lines at start of function, in my opinion it makes code much more readable. Can't really live without it. One of my favorite.
These save less lines, but allows for bracket-less action-log which in my opinion look more pleasant:
if ((f = fopen(file, mode) == NULL)
PERROR_RETURN(-1, "fopen has failed for file %s", file);
if (error_case)
PRETURN(-1, EIO, "spi device failed to respond");And few other - mostly - for debugging
for (...) {
if (not_this_case)
PCONTINUE(debug, "this is not it")
if (were_done)
PBREAK(debug, "loop reached the end");
64
Upvotes
10
u/pwnedary Oct 11 '26 edited Oct 11 '26
I am wary of macros with non-local control flow, c.f. Linus Torvalds's motivation for removing macros such as
copy_from_user_ret(). However, they can make loops easier to understand, for example:33
u/Interesting_Buy_3969 Oct 11 '26 edited Oct 12 '26
Doesn't need an example.
Yet this:
Example:
(I think this is a bad macro, honestly, but it's still my favourite.)
Edit: Note that the second macro requires this GNU extension: https://gcc.gnu.org/onlinedocs/gcc/Statement-Exprs.html
27
u/matt9k Oct 11 '26
Kinda stupid but
#define freenull(x) (free(x); (x) = NULL;)
19
u/tstanisl Oct 11 '26
C89 compliant
container_ofwith type checking:11
u/chrism239 Oct 11 '26
Place
CHECKALLOC(p)immediately after requesting a memory allocation, such asmalloc(),realloc(), orstrdup()-7
u/GrandBIRDLizard Oct 11 '26
Classic
6
u/zellforte Oct 12 '26
Couple cute ones I started using when doing some macro based generic code, check if an argument is a specific type, and if it's an array.
_Generic decays arrays to pointers, but not pointers to arrays (which is a distinct thing, don't forget), so as they say, throw an extra level of indirection to solve any problem...
#define IS_ARRAY(a) _Generic((typeof(a)*)0,typeof((a)[0])**: 0,typeof((a)[0])(*)[countof(a)]: 1)#define IS_TYPE(x,T) _Generic(x, T: 1,default: 0)//usage#define foo_action(T,a) do{\_Static_assert(IS_TYPE(T, struct foo), "T must be struct foo"); \_Static_assert(IS_ARRAY(a), "argument must be an array"); \// stuff.. \}while(0)5
u/TheChief275 Oct 11 '26
fun labeled loops trick:
used e.g. like so:
1
u/smcameron Oct 13 '26
It allows you to do things like:
in case struct some_struct needs to be on an 8 byte alignment, and catch it at compile time if it isn't true. It works by trying to talk about an array with a negative size in the event the assertion fails, which the compiler doesn't like. In the case the assertion is true, it emits no code. It does have to be used in a code block, as if it were a statement (because it is a statement.)
Cribbed from the linux kernel ages ago. Pretty sure there is a newer compiler-assisted way to do this now.
3
u/ffd9k Oct 11 '26
3
u/KanjiCoder Oct 14 '26
define VAR some_stupid_long_variable_name
... do stuff with VAR ...
undef VAR
^ 99% of my macros in PHOSIMP source code .
2
u/tastygames_official Oct 11 '26
here's my
assert:I saw some video from some guy talking about verbose asserts in PRODUCTION CODE and how big projects like MySQL (MariaDB) do this and it helps in two immense ways:
It was annoying at first, as I specifically didn't implement some things yet but still wanted to test, but nope - it forces me to have to implement it right away. My example was adding translation strings - if it didn't find one then it crashed. I wanted to just test to see if my hover effect worked and... CRASH. OK, I have to add the translation string - but then I won't have some weird bug later where a translation string is missing, which is often hard to detect. So overall a win!
2
u/tstanisl Oct 11 '26
The
ERR_ON(cnd, fmt, ...)that prints formatted error message if condition is true and returns the condition. This construct allows handling errors in very concise though still explicit way.2
u/greg_kennedy Oct 11 '26
i often end up with one that does "fread() check that count == return value, perror() and goto error: if not" for things like file parsing (read a few bytes at a time, then a few more, then some more in a loop, etc)
2
u/jwzumwalt Oct 11 '26
Common pre-defined macros
No Macro Description
1 _DATE_ current date in "MMM DD YYYY" format.
2 _TIME_ current time in "HH:MM:SS" format.
3 _FILE_ current file name.
4 _LINE_ current line number.
5 _STDC_ equels 1 if compiler meets ANSI standard.
example:
// File: simple.c ver 2023.07.01
#include <stdio.h>
int main(void) {
printf("File :%s\n", __FILE__ );
printf("Date :%s\n", __DATE__ );
printf("Time :%s\n", __TIME__ );
printf("Line :%d\n", __LINE__ );
printf("STDC :%d\n", __STDC__ );
return 0;
}
Output
--------
File :simple.c
Date :Dec 6 2015
Time :12:28:46
Line :6
STDC :1
1
u/mivanchev Oct 11 '26 edited Oct 11 '26
1
u/stianhoiland Oct 11 '26 edited Oct 11 '26
Here's how to use
each:I wish there was a way to make the macro define the
struct elementvariable scoped to theforloop and not have to inherit it, but you can't with current macro rules.1
u/Typical-Employment41 Oct 11 '26 edited Oct 11 '26
Ok not constantly but I like how this makes serialization a bit readable. And now I see how changing pBuff first and value last would make it even more readable
static void readEntryDataFromLogBuffer(struct LiSpLogEntry_data* pEntryData) { uint8_t* pBuf = m_liSpLogWriteBuffer; chArrayToValue_IncrementPtr(pEntryData->lightsOnTime_s, &pBuf); chArrayToValue_IncrementPtr(pEntryData->batteryChargingTime_s, &pBuf); chArrayToValue_IncrementPtr(pEntryData->passiveChargingTime_s, &pBuf); chArrayToValue_IncrementPtr(pEntryData->batteryLowest_mV, &pBuf); chArrayToValue_IncrementPtr(pEntryData->batteryHighest_mV, &pBuf); chArrayToValue_IncrementPtr(pEntryData->producedSolarPower_mJ, &pBuf); chArrayToValue_IncrementPtr(pEntryData->photocellReadingWhenChargingStartsFirstT ime_lx, &pBuf); chArrayToValue_IncrementPtr(pEntryData->temperatureLowest_dC, &pBuf); chArrayToValue_IncrementPtr(pEntryData->temperatureHighest_dC, &pBuf); chArrayToValue_IncrementPtr(pEntryData->alarms, &pBuf); chArrayToValue_IncrementPtr(pEntryData->entryAge_s, &pBuf); chArrayToValue_IncrementPtr(pEntryData->chargeState, &pBuf); }
static void writeEntryDataToLogBuffer(const struct LiSpLogEntry_data* pEntryData) { uint8_t* pBuf = m_liSpLogWriteBuffer;
valueToChArray_IncrementPtr(pEntryData->lightsOnTime_s, &pBuf); valueToChArray_IncrementPtr(pEntryData->batteryChargingTime_s, &pBuf); valueToChArray_IncrementPtr(pEntryData->passiveChargingTime_s, &pBuf); valueToChArray_IncrementPtr(pEntryData->batteryLowest_mV, &pBuf); valueToChArray_IncrementPtr(pEntryData->batteryHighest_mV, &pBuf); valueToChArray_IncrementPtr(pEntryData->producedSolarPower_mJ, &pBuf); valueToChArray_IncrementPtr(pEntryData->photocellReadingWhenChargingStartsFirstT ime_lx, &pBuf); valueToChArray_IncrementPtr(pEntryData->temperatureLowest_dC, &pBuf); valueToChArray_IncrementPtr(pEntryData->temperatureHighest_dC, &pBuf); valueToChArray_IncrementPtr(pEntryData->alarms, &pBuf); valueToChArray_IncrementPtr(pEntryData->entryAge_s, &pBuf); valueToChArray_IncrementPtr(pEntryData->chargeState, &pBuf); }
I wish reddit android app had rich editor...
1
u/gnuvince Oct 11 '26
1
u/paulkim001 Oct 12 '26
A bit clunky since it relies on existence of error_cleanup label, but I found it useful when I am allocating dynamically multiple things within a function and I need to handle errors.
1
u/bullno1 Oct 13 '26 edited Oct 13 '26
Not quite constantly but:
Used as:
I don't have to remember the
fam_typeand I can change it. There are ways to do compile time check thatfamis indeed the flexible member but I find it too convoluted so I stick to the most straightforward version.1
u/Layzy37 Oct 14 '26
I mostly use the classic variable arguments in c trick:
And here is an example in a real use case: