gpt4 book ai didi

c - C中的 bool 数组初始化

转载 作者:太空狗 更新时间:2023-10-29 16:28:36 24 4
gpt4 key购买 nike

我偶然发现了一些我在网上找不到任何信息的奇怪行为。如果我像这样初始化一个 bool 数组:

 bool condition[10] = {true,[5]=true};

我得到了我期望的输出,第一个和第六个值是真的,而其他的是假的。但是如果我写下面的片段:

 bool condition[10] = {true,condition[5]=true};

我将第一个、第二个和第六个值设为真。我认为这是某种未定义的行为,但我希望比我更有知识的人向我解释发生了什么。

我正在使用 GCC 和“-std=gnu99”使用额外的警告标志进行编译,但我没有收到任何错误。

最佳答案

C 说:

(C11, 6.7.9p23) "The evaluations of the initialization list expressions are indeterminately sequenced with respect to one another and thus the order in which any side effects occur is unspecified."

在 C99 中

(C99, 6.7.8p23) "The order in which any side effects occur among the initialization list expressions is unspecified."

也就是说声明

    bool condition[10] = {true,condition[5]=true};

可以有相同的行为:

    bool condition[10] = {true, 1};

或作为

    bool condition[10] = {true, 1, [5] = true};

condition[5] = true 评估是在数组成员的 0 初始化之前还是之后完成。

编辑:在缺陷报告 #208 中存在未指定数组元素初始化顺序的情况。情况有所不同,因为在 DR 示例中,单个元素有两个初始值设定项。

http://www.open-std.org/jtc1/sc22/wg14/www/docs/9899tc1/n32074.htm

int a [2] = { f (0), f (1), [0] = f (2) };

It was the intention of WG14 that the call f(0) might, but need not, be made when a is initialized. If the call is made, the order in which f(0) and f(2) occur is unspecified (as is the order in which f(1) occurs relative to both of these). Whether or not the call is made, the result of f(2) is used to initialize a[0].

关于c - C中的 bool 数组初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25470241/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com