使用宏在 C 中创建循环
在查看一些遗留代码时,我发现了一个相当不寻常的构造(至少对我来说):
#define loop(i,start,stop) for((i)=(start);(i)<(stop);(i)++)
然后在任何地方都使用这个宏,而不是常规的 for 循环构造。
我认为总的来说这是一个坏主意,因为它并没有真正解决问题也没有简化任何事情,但是它会危险吗? 我所说的危险是指破坏编译(最好的情况)或(更糟糕但更有趣)做一些超出预期的事情。
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 instead 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.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
针对宏的标准警示故事是带有副作用的参数:
The standard cautionary tale against macros is arguments with side effects:
虽然,我不建议这样做,因为它会使代码变得混乱且可读性较差(实际上并没有简化事情),但它在技术上没有任何问题。如果使用正确,它不会导致任何问题或意外行为。当然,如果像其他答案之一中提到的那样给出奇怪的论点,就会出现问题。
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.
它不太可能是危险的,但如果使用不当,它可能会做一些超出您预期的事情。问题是宏正在执行文本替换——它们可以在解析器看到代码之前对其进行尝试。这意味着如果你在 'i' 中做了一些有副作用的事情,那么你所做的任何事情都将被复制 3 次,而这可能不是你想要的。
如果你总是将它与简单变量一起使用,它总是会正确工作,但如果你变得复杂,你最好小心。
我个人不会使用它,因为我同意它不会简化任何事情。
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...