Is the following program a strictly conforming program in C? I am interested in c90 and c99 but c11 answers are also acceptable.
#include <stdio.h>
#include <string.h>
struct S { int array[2]; };
int main () {
struct S a = { { 1, 2 } };
struct S b;
b = a;
if (memcmp(b.array, a.array, sizeof(b.array)) == 0) {
puts("ok");
}
return 0;
}
In comments to my answer in a different question, Eric Postpischil insists that the program output will change depending on the platform, primarily due to the possibility of uninitialized padding bits. I thought the struct assignment would overwrite all bits in b
to be the same as in a
. But, C99 does not seem to offer such a guarantee. From Section 6.5.16.1 p2:
In simple assignment (
=
), the value of the right operand is converted to the type of the assignment expression and replaces the value stored in the object designated by the left operand.
What is meant by "converted" and "replaces" in the context of compound types?
Finally, consider the same program, except that the definitions of a
and b
are made global. Would that program be a strictly conforming program?
Edit: Just wanted to summarize some of the discussion material here, and not add my own answer, since I don't really have one of my own creation.
- The program is not strictly conforming. Since the assignment is by value and not by representation,
b.array
may or may not contain bits set differently froma.array
. a
doesn't need to be converted since it is the same type asb
, but the replacement is by value, and done member by member.- Even if the definitions in
a
andb
are made global, post assignment,b.array
may or may not contain bits set differently froma.array
. (There was little discussion about the padding bytes inb
, but the posted question was not about structure comparison. c99 lacks a mention of how padding is initialized in static storage, but c11 explicitly states it is zero initialized.) - On a side note, there is agreement that the
memcmp
is well defined ifb
was initialized withmemcpy
froma
.
My thanks to all involved in the discussion.