Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

for loop macro coding style

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?

like image 200
user2320888 Avatar asked Dec 14 '22 02:12

user2320888


1 Answers

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:

  • what is the upper bound? It is not so obvious it should be n.
  • what is the actual range for i?
  • it is 0 based?
  • does it include 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.

like image 164
chqrlie Avatar answered Dec 21 '22 08:12

chqrlie