Search code examples
visual-c++warningsinitialization

Potentially uninitialized local variable used? Why?


When I write this code and compile with /W4

long r;
__try { r = 0; }
__finally { }
return r;

I get:

warning C4701: potentially uninitialized local variable 'r' used

Why does this happen?

Edit (in 2024): This only happens in 32-bit mode, not 64-bit mode.


Solution

  • The compiler can't be sure the code inside of the try block will successfully run. In this case it always will, but if there's additional code in the try block r = 0 may never execute. In that case r is uninitialized hence the error.

    It's no different than if you said:

    long r;
    if(something) {
      r = 0;
    }
    return r;
    

    (where 'something' is pretty much anything other than a constant true value).