Oleg Tcaregorodtcev
Oleg Tcaregorodtcev

Reputation: 73

Uninitialized _Bool variable or struct field behaves strangely

The code below:

_Bool field0;
char field1;

printf("fieldX:                [%d]\t[%d]\n", field0,         field1);
printf("fieldX ? 1 : 0:        [%d]\t[%d]\n", field0 ? 1 : 0, field1 ? 1 : 0);
printf("!fieldX:               [%d]\t[%d]\n", !field0,        !field1);
printf("!!fieldX:              [%d]\t[%d]\n", !!field0,       !!field1);

Gives the following output:

fieldX:                [165]  [165]
fieldX ? 1 : 0:        [165]  [1]
!fieldX:               [164]  [0]
!!fieldX:              [165]  [1]

Looks quite surprising, especially ternary operator result.

Checked with gcc 4.9.3 and 4.8.3, -O0, no -flto.

Remark: the stack was previously initialized with 0xa5 pattern (embedded C environment).

Upvotes: 2

Views: 74

Answers (2)

ouah
ouah

Reputation: 145879

Accessing an uninitialized object with automatic storage invokes undefined behavior. So nothing strange here.

Moreover a _Bool object can only hold two values: either 0 or 1. An implementation is allowed to replace !!boolean_object or boolean_object ? 1 : 0 by boolean_object.

(Also note that even with -O0, gcc is still performing some optimizations: for example, it inlines static functions called once.)

Upvotes: 1

M.M
M.M

Reputation: 141618

Accessing an uninitialized automatic variable causes undefined behaviour in most cases, in this one.

See this thread for the exact details of "most".

Upvotes: 1

Related Questions