Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Boolean array initialization in C

Tags:

arrays

c

I've stumbled upon some weird behavior for which I couldn't find any info online. If I initialize a boolean array like this:

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

I get the output I expect, first and sixth values are true while others are false. But if I write following snippet:

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

I get first, SECOND and sixth values as true. I assume it's some kind of undefined behavior but I'd like someone more knowledgeable than me to explain to me what's going on.

I'm compiling with extra warning flags, using GCC and "-std=gnu99", and I'm not getting any errors.

like image 867
user3533671 Avatar asked Aug 24 '14 09:08

user3533671


2 Answers

C says that:

(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."

and in C99

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

That means that the declaration

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

can have the same behavior:

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

or as

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

whether condition[5] = true evaluation is done before or after the 0 initialization of the array members.

EDIT: there is a case of unspecified initialization order of array elements in Defect Report #208. The case is different because in the DR example there are two initializers for a single element.

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].

like image 179
ouah Avatar answered Oct 13 '22 22:10

ouah


That is a nice little puzzle. I think ouah got it, but more explanation would probably help. I think condition[5]=true is not a designated initializer. It is an expression, which evaluates to true as usual. Since that expression is in the second spot, true gets assigned to to condition[1]. Also, as a side-effect of the expression, condition[5] gets set to true.

like image 45
Neal Avatar answered Oct 13 '22 22:10

Neal