Why does a non-constant offsetof expression work?
Posted
by
Chris J. Kiick
on Stack Overflow
See other posts from Stack Overflow
or by Chris J. Kiick
Published on 2013-10-21T21:40:19Z
Indexed on
2013/10/21
21:53 UTC
Read the original article
Hit count: 145
Why does this work:
#include <sys/types.h>
#include <stdio.h>
#include <stddef.h>
typedef struct x {
int a;
int b[128];
} x_t;
int function(int i)
{
size_t a;
a = offsetof(x_t, b[i]);
return a;
}
int main(int argc, char **argv)
{
printf("%d\n", function(atoi(argv[1])));
}
If I remember the definition of offsetof correctly, it's a compile time construct. Using 'i' as the array index results in a non-constant expression. I don't understand how the compiler can evaluate the expression at compile time. Why isn't this flagged as an error?
© Stack Overflow or respective owner