Hi,
Variables are only available within the set of curly braces there are declared. This is called the SCOPE of the variable.
therefore your code snipet....
if(first)
{
int j=0;
}
j is only available between the braces. if your code really looked like....
if(first)
{
int j=0;
}
j++;
you will get a j not declared because you are trying to to use j ourside the SCOPE that j is declared.
A variable can have multiple SCOPES.
func()
{
int j;
if(first)
{
int j=0;
j++
}
j += 5;
you would actually have 2 different variables called 'j'.
One whose scope is the WHOLE function except for the inside the if (first) and a sceond whose scope is just inside the if statement. j += 5 could be any random value becasue j in the Outer SCOPE has never been properly initialized.
This just causes confusion in most programs and should be avoided.
The above posts define how to declare j at the appropriate SCOPE.
func()
{
int j;
if(first)
{
j=0;
}
}
However, no where did I see where you had decalred first. first has the same issues as 'j'.
func()
{
BOOL first = 0;
int j;
if ( first )
{
j = 0;
first = FALSE;
}
.
.
.
}
The next time you come into the function 'first' will again be initialized to '0' and you will again initialize 'j' to 0. kind of a circular problem.
Now I supoose you could pass first in a paramter to func().
Therefore if you really only want to initialize 'j' to 0 the first time the function is called then use the STATIC declaration.
func()
{
static j = 0;
j ++;
.
.
.
}
This will initialize 'j' to 0 when the program starts and it retain the value in 'j' accross the function calls.
Now this works fine unless you are running multiple threads in your application in which case it is possible for 2 people to execute this code simultaneously in which case you need to use a locked Add to make sure only one thread bumps it a time or declare 'j' to be Thread Specific in which case each thread will get their own private copy of 'j'.