需要帮助将 C 宏重写为函数
我需要一些帮助以更类型安全的方式重写以下行并将其重写为函数,但是该代码是在函数内部定义的事实使我很难想到一种聪明的方法,因为显然它将涉及声明几个参数。
#define CHECK(id) if(table->cells[id]) isgood[table->cells[id]-1] = 0;
其中table
是一个struct
,isgood
是一个int
。
I need some help rewriting the following line in a more type safe way and rewriting it as a function, however the fact that this code is defined inside a function is making it hard for me to think of a clever way of doing it because apparently it would involve declaring several arguments.
#define CHECK(id) if(table->cells[id]) isgood[table->cells[id]-1] = 0;
where table
is a struct
and isgood
is an int
.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
直接翻译(如果 table->cells[id] 是 int):
调用:
但是,我会对此进行重命名/修改。 我特别想改一下名字。 也没有错误检查 - 即,如果 table->cells[id]==0,您将尝试设置 isgood[-1],这会很糟糕。
Straight translation (if table->cells[id] is int):
Call with:
However, I'd rename/rework this a bit. I'd especially change the name. There is also no error checking - ie, if table->cells[id]==0, you're going to try to set isgood[-1], which would be bad.
有什么问题吗?
What is wrong with that?
为什么不只是一个接收
table
和id
的函数来执行此操作呢?ps
这确实是一个糟糕的宏。 这个名字很有误导性。
pps
整个事情相当奇怪,我无法理解这个函数的逻辑。 这究竟要达到什么目的?
Why not just a function that receives
table
andid
and does this?p.s.
It's a bad macro indeed. The name is very misleading.
p.p.s.
The whole thing is rather weird and the logic of this function escapes me. What exactly is this supposed to achieve?
如果您使用 C++,我会考虑将 check 作为表的成员函数,这似乎是一个很好的候选类:
If you're working in C++, I'd consider making check a member function of the table, which seems like a good candidate for a class:
通常最好不要在宏中引用变量。
首先,确保名称有意义。 你在检查什么? 还有副作用吗?
It is generally a good idea not to refer to variables in a macro.
First, make sure the name is meaningful. what are you checking for? And is there a side effect?
我认为 C99 可以将函数限定为内联函数,这样您就可以在不使用宏的情况下获得无函数调用的加速。 此外,大多数 C 编译器都支持 __inline 等扩展来实现此目的。
I think C99 can qualify functions as inline so you get the speedup of no-function-call without using macros. Also, most C compilers support extensions such as __inline for this purpose.