Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

This example is clearly UB.

You could argue that it suddenly becomes less UB if you take the address of x:

  unsigned int x;
  &x;
  x -= x;
I'm not sure if this will add anything to the discussion on SO, but if you allow programs to do this, then after applying modern optimizing C compilers, you may end with multiplications by 2 that produce odd results, or uninitialized char variables that contain 500: http://blog.frama-c.com/index.php?post/2013/03/13/indetermin...

So the short answer is that, for all intent and purposes, you should consider use of uninitialized variables as UB, because C compilers already do. (There exists somewhere a document clarifying what C compilers can and cannot do with indeterminate values. A search for “wobbly values” might turn it up. Anyway, you do not want to have wobbly values in your C programs any more than you want it to have undefined behavior.)



Interesting link, thanks. So then:

* Under C90, reading an uninitialized local was explicitly listed as UB.

* Under C99, if you weren't using a character type, it was still essentially UB, by way of trap values. (I don't think the particulars of the target hardware platform are relevant.)

* C11 reintroduced UB even for some cases involving character types. We were already invoking UB under C99, so we know we're still invoking UB under C11.

> You could argue that it suddenly becomes less UB if you take the address of x

I don't think so. As we're not using a character type, I don't think taking its address would change anything. This aligns with what msebor said.

Lastly, from the article:

    > No, GCC is still acting as if j *= 2; was undefined.
I think GCC's behaviour is legal here. The target platform may have no trap values, but I don't see that GCC is prohibited from behaving as if there are. It would be legal (albeit bizarre) for it to generate code for a completely different ISA, and to bundle an emulator. If the spec says you've opened the door to UB, then unless your compiler documentation says otherwise, it's permitted to generate code that goes haywire, no?




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: