16

I wanted to see if I could initialize a global variable to point to itself:

#include <stdio.h>
struct foo { struct foo *a, *b; } x = { &x, &x };
int main()
{
    printf("&x = %p, x.a = %p, x.b = %p\n", &x, x.a, x.b);
    return 0;
}

This code compiles and runs as expected with gcc (all three pointers print identically).

I want to know:

  1. Is this reliable?
  2. Is this standard?
  3. Is this portable?

EDIT: Just to clarify, I am questioning the availability of the address of x in its own initializer.

4

2 回答 2

8

是的以上所有。您有几个使用相同地址初始化的指针,因此它们拥有相同的地址,这与您初始化它们时使用的地址相同。

或许更有趣的x.a是,也保证指向自身(即,结构中的第一个元素保证在结构的最开始,因此保证了指向结构的指针,转换为第一个元素的类型指向第一个元素。

于 2012-05-29T20:45:47.300 回答
8

这是标准的 C 代码。

强大标准的这一段允许它(强调我的):

(C99,6.2.1p7)“结构、联合和枚举标记的范围在标记出现在声明标记的类型说明符之后开始。每个枚举常量的范围都在其定义的枚举数出现之后开始在枚举器列表中。任何其他标识符的范围都在其声明符完成后开始。

有关信息,请注意,为了说明 6.2.1p7 的最后一句话,Derek M. Jones 的“新 C 标准”一书使用了与您的示例类似的示例:

struct T {struct T *m;} x = /* declarator complete here. */ {&x};
于 2012-05-29T21:07:43.800 回答