Question on Variable Initial value in a for loop

Technical questions regarding the XTC tools and programming with XMOS.
bearcat
Respected Member
Posts: 283
Joined: Fri Mar 19, 2010 4:49 am

Question on Variable Initial value in a for loop

Post by bearcat »

Take the following code snippet:

Code: Select all

	for(int i = 0; i < MAX; i++)
    {
		unsigned zeroflag = 0;
		if (zeroflag == 0)
        {
            L[i] = l[i];
            R[i] = r[i];
            if (i >= size)
            {
            	zeroflag = 1;
            }
        }
        else
This code doesn't work with the zeroflag. The if is always true.
I had expected the zero flag to be initialized only once, or something like that? If I move the assigment outside the for loop, it works. Does this mean in XC I cannot perform variable initialization inside a for loop? That seems like an issue I would really need to know: You can't declare variables with a scope of the for loop? Maybe this is standard C stuff?? Did a little googling and didn't find anything.


User avatar
Bianco
XCore Expert
Posts: 754
Joined: Thu Dec 10, 2009 6:56 pm

Post by Bianco »

bearcat wrote:Take the following code snippet:

Code: Select all

	for(int i = 0; i < MAX; i++)
    {
		unsigned zeroflag = 0;
		if (zeroflag == 0)
        {
            L[i] = l[i];
            R[i] = r[i];
            if (i >= size)
            {
            	zeroflag = 1;
            }
        }
        else
This code doesn't work with the zeroflag. The if is always true.
I had expected the zero flag to be initialized only once, or something like that? If I move the assigment outside the for loop, it works. Does this mean in XC I cannot perform variable initialization inside a for loop? That seems like an issue I would really need to know: You can't declare variables with a scope of the for loop? Maybe this is standard C stuff?? Did a little googling and didn't find anything.
This is the same behaviour as in C and pretty standard ;).
You have to initialize the zero flag outside the loop.

Basically your code reads like this:

for all interations:
create a new variable zero_flag and initialize it to zero.
check if zero_flag is zero.

Of course zero_flag will always be zero :).

you might be confused with the static modifier?
bearcat
Respected Member
Posts: 283
Joined: Fri Mar 19, 2010 4:49 am

Post by bearcat »

Thanks for the C tip. Mental note made. I will have to review all my code for this.

Would this be true for a while loop also?
User avatar
segher
XCore Expert
Posts: 844
Joined: Sun Jul 11, 2010 1:31 am

Post by segher »

Yes, it is true for any automatic variable.

In C, you would typically use a "static" (block scope) variable. In XC, this
is not allowed.