Skip to main content
GameDev.net gamedev.net
🔒 Locked

c++ error: warning C4700: uninitialized local variable 'k' used

Started by ??????????????? Dec 8, 2011 at 5:28 PM 4 replies 44.9k views
Original Post
???????????????
???????????????
can anyone tell me what's the problem here?

warning C4700: uninitialized local variable 'k' used


#include
#include
#include
using namespace std;
int abs(int );
void cube(int );
void printVector(vector );
vector v;
int main()
{
int a,c;
int k;
while(cin>>a)
v.push_back(a);
printVector(v);
cube(k);
for(int i=0; i {
c=abs(v);
cout< }
cout< }
void printVector(vectorv)
{
for(int i=0; i< v.size(); i++)
cout<<<'\t';
cout< }
void cube(int x)
{
for(int i=0; i< v.size(); i++)
{
x=v*v*v;
cout< }
cout< }
yewbie
yewbie
Your using the variable k without giving it "default" value.

This warning will go away if you do this:
int k = 0;

Its just a warning and your overwriting whatever value happens to be there for your variable k anyway.
pulpfist
pulpfist
You are using the variable k without giving it a sane value first.
The compiler you are using consider this to be worth a warning.

Basically, after declaring and defining the variable k:

int k;

its contents is undefined and can be any value.
juliano7s
juliano7s
The warning is there to warn (obviously) you that you may have problems if you do not initialize the variable, as pulpfist said, it can have any value (trash) in it.
http://www.creationguts.com - The Guts of Creation
drawing, programming and game design.
rip-off
rip-off
There is no reason to have X as an argument to cube. Cube could be written as:

void cube()
{
for(int i = 0 ; i < v.size() ; i++)
{
int x = v * v * v;
cout << x << '\t';
}
cout << endl;
}

Once you have done this, it is easy to remove "k" from the calling function.

You should also scope your variables as tight as possible. Note I declared "x" inside the loop in the above example. Likewise, the variable "c" in main() could be declared inside the loop.

There is plenty reason to add "v" as an argument to cube. It means the function could be re-used to show the cubed values of any vector.

void cube(vector<int> v)
{
for(int i = 0 ; i < v.size() ; i++)
{
int x = v * v * v;
cout << x << '\t';
}
cout << endl;
}

Passing v by const reference would be even better (saves an unnecessary copy of a potentially very long vector).

You could then move "v" to be local to main(), rather than a global. Globals are generally poor design, they create bug prone code which relies on the caller remember to set the state of the global correctly, and cases where two or more callers "fight" over the state of the global, which can cause extremely difficult to reproduce bugs.

Finally, do not declare functions that you intend to use from the standard library. Remove the declaration of "abs".

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.