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?
Asked
Active
Viewed 2,951 times
6

Manish Burman
- 3,069
- 2
- 30
- 35
-
1http://stackoverflow.com/questions/4114982/compile-time-operators – Aziz Jan 22 '12 at 06:48
-
C++ isn't a strict superset of C though – Manish Burman Jan 22 '12 at 06:51
-
2then it's only sizeof, as Nic indicated in his answer. Keep in mind that any operator can be compile-time when you provide constants to it (e.g.`4*8` or `2<<5` will be replaced with 32 at run time). – Aziz Jan 22 '12 at 06:56
-
I can think of `-` in `&a[constant1]-&a[constant2]`, where `a` is an array (or a pointer). – Alexey Frunze Jan 22 '12 at 07:25
-
@Alex: that's a particular expression involving `-`, that could be evaluated at compile time because of some useful property of the operands. It's a different thing from `-` itself being a "compile-time operator" – Steve Jessop Jan 22 '12 at 11:24
4 Answers
3
Only sizeof
that I'm aware, although in C99 sizeof cannot be done at compile time for variable length arrays (VLAs).

Nic Foster
- 2,864
- 1
- 27
- 45
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:

R.. GitHub STOP HELPING ICE
- 208,859
- 35
- 376
- 711
2
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);
}

Lindydancer
- 25,428
- 4
- 49
- 68