这效率低吗?
扩展这个问题,我想使用我的枚举 val 因为它们“应该”是,
#include <stdio.h>
enum E{ A, B, C } ;
#define inc(enVal) (*((int*)&enVal))++
int main()
{
E t = A ;
inc( t ) ;
printf( "t %d\n", t ) ;
}
现在呃,t
是一个枚举类型 E 的变量,并且我有一个宏 inc
可以增加的值t
减 1,
那么这个宏(大概还有类似用于标志检查的其他宏)会比仅使用 int t
效率低得多吗?
Extending this question, I wanted to use my enumed val as they're "supposed" to be,
#include <stdio.h>
enum E{ A, B, C } ;
#define inc(enVal) (*((int*)&enVal))++
int main()
{
E t = A ;
inc( t ) ;
printf( "t %d\n", t ) ;
}
Now uh, t
is a variable of enum'd type E, and I have a macro inc
that increases the value of t
by 1,
So is this macro (and presumably other macros like it for flag checking) going to be that much less efficient than just using int t
instead?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
不,效率不会降低。然而,这将是令人难以置信的、可怕的、错误的。拜托,永远不要。
哦,特别是因为枚举的支持类型未定义,并且在某些编译器上它们实际上很可能被编译为小于
int
的大小。No, it's not going to be less efficient. It will, however, be incredibly, hideously, wrong. Please, don't ever.
Oh, especially since the backing type of enums is undefined and they might well actually be compiled to less than the size of an
int
on some compilers.来吧,枚举重载是可以的:
请参阅实际操作。
Come on, it's ok to overload for enums:
See in action.
我非常确定这违反了标准中的严格别名规则,而且它不仅根本不适用于
C
。你到底想做什么?增加这个值真的有意义吗?假设您正在尝试实现一个状态机,更好的方法是拥有一个向量/数组查找表并使用它来移动到新状态。
如果您希望能够假设枚举值是连续的,您确定不应该只使用
int
吗?I'm pretty sure this violates the strict-aliasing rules in the standard, and not only that it won't work right for
C
at all. What are you really trying to do? Does it actually make SENSE to increment the value?Say you're trying to implement a state machine, much better is to just have a
vector
/array lookup table and use that to move to a new state.Are you sure you shouldn't just be using an
int
instead, if you want to be able to assume that the enumerated values are consecutive?