Search code examples
c++undefined-behaviorunsigned-integer

Is using an uninitialized unsigned type object Undefined Behavior?


I know that using (accessing the value) an uninitialized non-static and non-global object of type built-in integral type is Undefined behavior.

int x; // x is defined inside a function scope for example main
++x;// UB

signed char c = 127; // max positive value for char on my machine

c++; // UB overflowing a signed char.
  • Until here it is OK but what about unsigned types?

       unsigned char uc = 255; // ok
       uc++; // ok c now has the value 0
    

It is OK here because overflowing an unsigned will discard the bits outside the range.

  • So as long as any value assigned to an unsigned is it harmless to do this:

    unsigned int x; // local non-static uninitialized
    
    std::cout << x << '\n';// is it UB or OK?
    
  • AS you can see that any (indeterminate) value set to an unsigned doesn't cause a UB so is it wrong to do so?

  • I don't matter what value in x but I think it doesn't cause any harm.

  • If it is OK then I guess it looks like a random value can be generated by the compiler from using an uninitialized unsigned non-static non-global object.


Solution

  • Is using an uninitialized unsigned type object Undefined Behavior?

    Yes.

    but I think it doesn't cause any harm.

    You might be right. But since it's UB you might also be wrong. You can never be sure.

    One sneaky thing compilers do is detect your Undefined Behavior and "optimize" your program by outright removing code paths that reach this UB.

    Example (program compiles, but does nothing)