Oleg Tcaregorodtcev Oleg Tcaregorodtcev - 1 year ago 66
C Question

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

Answer Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download