How can I obtain a value from inside a for loop?
I declared the variable in the method and not inside the loop. When I use the same variable in an if statement in the same method however, I get a message saying that the variable has not been initialized. I want to use the value of the variable that has ibeen initialized inside the for loop in my if statement. I dont want to however, put the if statement inside the for loop.
Any suggestions?
Thanks!!!!!!!!

Recommended Answers

All 2 Replies

so? Initialise the variable before using it.

Lets say you are using an integer as a counting variable:

int x;
for (x=0;x<10;x++){}
//remainder of your code here

If you want to access the value of x later the for-loop may not have been evaluated if the condition was Never met, so x would be lacking a value, potentially causing issues later in the code. To avoid this, simply initialize the variable outside the loop and modify it inside the loop as required:

int x = 0;
for (x=0;x<10;x++){}
//remainder of your code here
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.