数组初始化中的数组元素分配 [英] Assignment of array elements in array initialization

查看:79
本文介绍了数组初始化中的数组元素分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑以下简单程序:

#include <stdio.h>

int main(void)
{
    int a[5] = { a[2] = 1 };
    printf("%d %d %d %d %d\n", a[0], a[1],a[2], a[3], a[4]);
}

在GCC 7.3.0中,此输出

With GCC 7.3.0 this outputs


1 0 1 0 0

考虑到a[1]为零,似乎初始化类似于

Considering that a[1] is zero, it seems that the initialization is similar to

int a[5] = { 1 };
a[2] = 1;

问题是:尽管初始化器可以是任何通用表达式,但初始化和分配是按什么顺序进行的?

The question is: While initializers could be any generic expression, in which order is the initialization and assignments made?

这是否有效且定义明确?是实现定义的,未定义的还是未指定的?

Is this even valid and well-defined? Could it be implementation-defined, undefined or maybe unspecified?

此问题与问题关于C语言中的数组初始化的混淆

推荐答案

虽然我无法声明自己是ISO专家,但这是我在

While I cannot state, that I am an ISO-expert, here is what I found out with the help of godbolt.

首先,我在 -fsanitize=undefined 的帮助下构建了示例>,这很好地表明了未定义的行为. GCC和c都没有抱怨.

First I built the sample with the help of -fsanitize=undefined, which gives a good indication of undefined behavoir. Neither GCC nor clang were complaining.

接下来,我研究了gcc执行的各个阶段,在这种情况下, gimple 阶段

Next I looked at the various stages gcc performs, in this case the gimple stage

foo ()
{
  int a[5];

  try
    {
      # DEBUG BEGIN_STMT
      a = {};
      a[2] = 1;
      _1 = a[2];
      a[0] = _1;
      # DEBUG BEGIN_STMT
      _2 = a[4];
      _3 = a[3];
      _4 = a[2];
      _5 = a[1];
      _6 = a[0];
      printf ("%d %d %d %d %d\n", _6, _5, _4, _3, _2);
    }
  finally
    {
      a = {CLOBBER};
    }
}

在这里您可以看到,首先定义了数组a,然后将1分配给了a[2],然后将结果分配给1,因为

Here you can see, that first the array a is defined, then 1 is assigned to a[2], afterwards that result (1, because it is an assignment) is assigned to the first element of a. The other in indices are left to 0 and therefore the pattern 1 0 1 0 0 is printed out.

这篇关于数组初始化中的数组元素分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆