One of my tutors at university suggests using macros to reduce repetition in c99 code, like this.
#define foreach(a, b, c) for (int a = b; a < c; a++)
#define for_i foreach(i, 0, n)
#define for_j foreach(j, 0, n)
#define for_ij for_i for_j
Which can be used like this:
for_ij { /*do stuff*/; }
for_i { /*do stuff*/; }
Another tutor with industrial background discourages its use, claiming it was seen as an anti-pattern at his former employer (but he does not know the reason behind this) . In fact by grepping through source code of large projects one rarely finds those constructs outside of short academic examples.
My question is: why is this construct so rarely used in practice? Is it dangerous to some extent?
This is such a perfect illustration of the gap between academia and the real world, it is hard to believe. But it looks too weird to be made up.
To answer your question: NO this kind of construction is not used in practice and it is risky as it hides information, using implicit variables and conditions.
Here are some questions the casual reader will ponder about:
n
.i
?0
based?n
or stop before?C programmers are very good at reading idiomatic constructions such as
for (int i = 0; i < n; i++) {
...
}
Hiding the details of this loop logic saves nothing, is counter-productive, error prone and should be outlawed by local coding conventions. The only reason it isn't in my teams is nobody came up with such a weird idea.
You may need to use caution with the university tutor who wants these abbreviations used, possibly an APL nostalgic, and avoid conflict. You might want to play some code golfing with him, there is a stack exchange dedicated to that and he will love how people waste countless hours shaving bytes from their source codes...
But you should follow the other tutor's advice and write clear and explicit code, carefully indented and spaced out, with meaningful names where it matters and short ones where their use is obvious. Favor idiomatic constructions where possible as it makes the code more readable, less error prone and better fit for optimizing compilers.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With