Compiler Warning (level 1 and level 4) C4700
uninitialized local variable 'name' used
Remarks
The local variable name has been used, that is, read from, before it has been assigned a value. In C and C++, local variables aren't initialized by default. Uninitialized variables can contain any value, and their use leads to undefined behavior. Warning C4700 almost always indicates a bug that can cause unpredictable results or crashes in your program.
To fix this issue, you can initialize local variables when they're declared, or assign a value to them before they're used. A function can be used to initialize a variable that's passed as a reference parameter, or when its address is passed as a pointer parameter.
The /sdl
(Enable Additional Security Checks) compiler option elevates this warning to an error.
Example
This sample generates C4700 when variables t
, u
, and v
are used before they're initialized, and shows the kind of garbage value that can result. Variables x
, y
, and z
don't cause the warning, because they're initialized before use:
// c4700.cpp
// compile by using: cl /EHsc /W4 c4700.cpp
#include <iostream>
// function takes an int reference to initialize
void initialize(int& i)
{
i = 21;
}
int main()
{
int s, t, u, v; // Danger, uninitialized variables
s = t + u + v; // C4700: t, u, v used before initialization
std::cout << "Value in s: " << s << std::endl;
int w, x; // Danger, uninitialized variables
initialize(x); // fix: call function to init x before use
int y{10}; // fix: initialize y, z when declared
int z{11}; // This C++11 syntax is recommended over int z = 11;
w = x + y + z; // Okay, all values initialized before use
std::cout << "Value in w: " << w << std::endl;
}
When this code is run, t
, u
, and v
are uninitialized, and the output for s
is unpredictable:
Value in s: 37816963
Value in w: 42