0

I recently learned that copying partially initialized structures through trivial construction or assignment is undefined in C++. Does the same hold true in C or does the standard guarantee that initialization and assignment behave like memcpy?

typedef struct { int i; int j; } A;

void foo() {
   A x;
   x.i = 0;
   // Leave x.j indeterminate. Is the following well defined?
   A y = x;
   y.j = y.i + 1;
}
Community
  • 1
  • 1
precarious
  • 598
  • 2
  • 14

1 Answers1

1

x is not "partially initialized" this is not initialized at all. Reading x in your initializer for y propagates the "indetermined" valueness (if one can say so) to y. If int could have trap representations on your platform, this already would be an error. But then you don't read that indeterminate field y.j, so there no problem at that particular assignment.

Jens Gustedt
  • 76,821
  • 6
  • 102
  • 177
  • 1
    Is `A y = x;` itself an error if `x.j` contains a trap representation? – precarious Oct 16 '15 at 14:52
  • 1
    If it *is* a trap, yes. But architectures that have trap representations for integers are rare nowadays, so this is more a theoretical question. And it is theoretical, anyhow, since a good programmer always initializes their `struct` variables, don't they. – Jens Gustedt Oct 16 '15 at 15:45
  • @JensGustedt: Even **if** there was a trap representation, would copying the whole `struct` it not just copy that pattern and not trap unless the copied field is accessed explicitly? IOW: does accessing a whole `struct` which contains trap representations also trap? – too honest for this site Oct 16 '15 at 17:33
  • @Olaf, no, you could for example `memcpy` it, which is different from `=`. The thing here is that intialization and assignment are defined recursively, initializing/assigning the individual fields, and would also work for address-less objects, e.g `register`. So then the trapping field is read, and an attempt to interpret it within its type is made. – Jens Gustedt Oct 16 '15 at 18:46
  • @JensGustedt: Many kinds of structures contain a number of fields which are sometimes relevant and sometimes not. Efficiency is not improved by requiring that programs must either spend time populating meaningless fields or spend more time avoiding copying meaningless fields than would be required to blindly copy them. – supercat Oct 11 '16 at 19:02
  • @supercat, I don't understand why your are telling me this, and why here at this old question. This is just bringing the news how things are in C as it stands. In the case of this question, an initialization to `x` wouldn't do any harm. Any decent optimizing compiler can figure out the parts that are never used and optimize them out. – Jens Gustedt Oct 12 '16 at 08:24
  • @JensGustedt: I was intending to respond to "a good programmer always initializes their struct variables"--I couldn't tell whether you were being sarcastic. – supercat Oct 12 '16 at 14:47