Is using a structure without all members assigned undefined?

后端 未结 4 591
囚心锁ツ
囚心锁ツ 2020-12-28 19:51

Consider this code in block scope:

struct foo { unsigned char a; unsigned char b; } x, y;
x.a = 0;
y = x;

C [N1570] 6.3.2.1 2 says “If the

4条回答
  •  無奈伤痛
    2020-12-28 19:58

    The C Standard specifies that structure types cannot have trap representations, although members of structs may. The primary circumstance in which that guarantee would be useful would be in cases involving partially-written structures. Further, a prohibition on copying structures before one had written all members, even ones the recipient of the copy would never use, would require programmers to write needlessly-inefficient code and serve no useful purpose. Imposing such a requirement in the name of "optimization" would be downright dumb, and I know of no evidence that the authors of the Standard intended to do so.

    Unfortunately, the authors of the Standard use the same terminology to describe two situations:

    1. Some implementations define the behavior of some action X in all cases, while some only define it for some; other parts of the Standard define the action in a few select cases. The authors want to say that implementations need not behave like the ones that define the behavior in all cases, without revoking guarantees made elsewhere in the Standard

    2. Although other parts of the Standard would define the behavior of action X in some cases, guaranteeing the behavior in all such cases could be expensive and implementations are not required to guarantee them even cases where other parts of the Standard would define them.

    Before the Standard was written, some implementations would zero-initialize all automatic variables. Thus, those implementations would guarantee the behavior of reading uninitialized values, even of types with trap representations. The authors of the Standard wished to make clear that they did not want to require all implementations do likewise. Further, some objects may define the behavior of all bit patterns when stored in memory, but not when stored in registers. Such treatment would generally be limtied to scalar types, however, rather than structures.

    From a practical perspective, defining the behavior of copying a structure as copying the state (defined or indeterminate) of all fields would not cost any more than allowing compilers to behave in arbitrary fashion when copying partially-written structures. Unfortunately, some compiler writers erroneously believe that "cleverness" and "stupidity" are antonyms, and thus behave as though the authors of the Standard wished to invite compilers to assume that programs will never receive any input that would cause structures to be copied after having been partially written.

提交回复
热议问题