Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#define for pedagogical purposes

Tags:

c

I would like to hide some complexity from some non-trivial code I'm writing. Here, I would like to hide one level of indirection from a struct pointer, to make it more readable. I'm not asking whether this is clean or a best practice or not, I know it isn't, but I also know what I like to achieve :)

So, how kosher is to have something like

#define getmark() m->o->marked

besides that fact that I would not write it in non-academic code? That would allow me to do

n->getmark()

, which is nicer (and more to the point than)

n->m->o->marked

Is the #define code correct? Will it just do a text replace here with no other strings attached?

like image 917
Dervin Thunk Avatar asked Jan 25 '26 01:01

Dervin Thunk


2 Answers

IMHO, most C programmers would prefer a function-style macro, like:

#define getmark(m) ((m) && (m)->o ? (m)->o->marked : -1)
like image 120
wildplasser Avatar answered Jan 27 '26 19:01

wildplasser


Quite frankly - not.

You are not making your code eaiser to read, but instead hiding the fact that there is a hidden state machine (m pointer which points to o).

You also make this hack global - which might break if someone has such variables.

Also ... the trick of adding "()" after the macro to make it look like you are calling a normal function, instead of 2 indirections... is bad. It looks for a reader like there should be a function with this name, but instead you hide a monster (poker face....).

If you need to simplify the state machine, and you know that there will be only one state - create a global static variable and create plain functions to call those objects.

like image 24
elcuco Avatar answered Jan 27 '26 20:01

elcuco



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!