Compile time operators in C

不问归期 提交于 2019-12-06 07:04:36

问题


I'm familiar with only one compile time operator in C - sizeof. Are there any others that I as a programmer should be aware of?


回答1:


Only sizeof that I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).




回答2:


I think what you're grasping for but missing the terminology to describe is a constant expression or integer constant expression. The results of certain operators can be (integer) constant expressions if their operands are, and as you've pointed out, the result of sizeof can be even if its operand is not constant as long as it's not a VLA. See 6.6 in C99:

http://port70.net/~nsz/c/c99/n1256.html#6.6




回答3:


The new C standard also has _Alignof that works similar to sizeof.




回答4:


Although not strictly an operator, there is offsetof, a macro defined in stddef.h. It is used to get the offset of a field member in a struct. For example:

#include <stddef.h>
struct my_struct
{
  int alpha;
  int beta;
};

int get_offset_to_beta(void)
{
  return offsetof(struct my_struct, beta);
}


来源:https://stackoverflow.com/questions/8959529/compile-time-operators-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!