开发者

using a macro to create a loop in C

While looking on some legacy code, I found a rather unusual construction (for me at least):

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

This macro is then used everywhere instea开发者_如何学Cd of regular for loops construction.

I think it's a bad idea in general because it does not really solve a problem nor simplify anything, but can it be dangerous? By dangerous I mean breaking compilation (best case) or (much worse but more interesting) do something else than expected.


The standard cautionary tale against macros is arguments with side effects:

loop(i, x, y++)


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


It's not LIKELY to be dangerous, but if used improperly, it could do something other than what you expect. The thing is that macros are doing TEXT replacement - they get to have a go at the code before the parser sees it. That means that if you do something in 'i' that has side effects, then whatever you've done will be replicated 3 times, and that might not be what you want.

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

I personally wouldn't use it because I agree that it doesn't simplify anything.


Maybe it should be avoided just because we have to think twice of potential side effects before using it. And so will the next programmer working on that code...

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜