Using a macro to create a loop in C

Looking at some kind of legacy code, I found a rather unusual construct (at least for me):

#define loop(i,start,stop) for((i)=(start);(i)<(stop);(i)++) 

This macro is used everywhere, not a regular construct for .

I think this is a bad idea in general, because it really does not solve the problem and does not simplify anything, but can it be dangerous ? For dangerous ones, I mean breaking the compilation (the best case) or (which is much worse, but more interesting) to do something else than expected.

+4
source share
4 answers

The standard warning story against macros is arguments with side effects:

 loop(i, x, y++) 
+6
source

While I would not advise this because it makes the code confusing and less readable (without actually simplifying things), there is nothing technically wrong with that. When used properly, it should not cause any problems or unintentional behavior. Of course, if strange arguments are given, as mentioned in one of the other answers, problems will arise.

+2
source

This is not dangerous, but if used improperly, it can do something else other than what you expect. The fact is that macros make a replacement for TEXT - they get access to the code before the parser sees it. This means that if you do something in "i" that has side effects, then everything you did will be replicated 3 times, and this may not be what you want.

If you always use it with simple variables, it will always work correctly, but if you get complicated, you better be careful.

I personally will not use it because I agree that it does not simplify anything.

+1
source

Perhaps this should be avoided only because before using it, we should think twice about potential side effects. And so will the next programmer working on this code ...

0
source

All Articles