Link to home
Start Free TrialLog in
Avatar of CrypToniC
CrypToniCFlag for Sweden

asked on

FOR loop variable

What happens with X in the following code ? Where is it stored ? How many times is it stored ?
(Basically what would the assembly look like ?)

for( int i=0;i<i+1; i++ )
{
  unsigned char X;<- What happens here ?
  do_something( &X );
}

Is there any difference if it would have
been
unsigned char X=1; ??

ASKER CERTIFIED SOLUTION
Avatar of rbr
rbr

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of CrypToniC

ASKER

Locally on the stack only
initialized (and copied) once ?

BTW yez it does overflow but it was
just a silly example :)
Avatar of rbr
rbr

yes initalized onced. What to you mean with copied?
No! Your X is going to get initialized every time! So, once ur loop i executed, x is reinitialized during the next runof ur loop! By the way, it's dangerous to use ur comparison statement x<x+1 -- it'll always be so!! Stack dump indeed -- try using UNIX u'll be CORE-Dumped!  
Pls read my answer carefully. I said x becomes 1 at the start at loop I mean it is intialized once for a loop.
People forget about the syntax for the
darn FOR - loop it is not interesting

rbr - one last thing
Would you initialize X inside the FOR
or outside, consider the case where
x: unsigned char X . No initialization
is done

BTW if i is a 16-bit number
wouldn't for( i;i<i+1;i++)
be equal to for( ;; ), since 32767<(32767+1 == -32768) Why would it neccessarily mean a stack dump ?
It depends on what you want to do.

e.g.

int main (int argn,char *argv[])
{

    int i;  
    printf ("Start");
 
   for (i=0;i<5;i++) {
       int j=1;
       j*=j;

       printf ("%d",j);
   }
   return 0;
}

and

int main (int argn,char *argv[])
{

   int i;  
   int j=1;
   printf ("Start");
 
   for (i=0;i<5;i++) {
       j*=j;

       printf ("%d",j);
   }
   return 0;
}

will lead to the same result. The differnces is that in the first example j is not accessable from outside the loop. (you could have a differnet j outside to loop)

32767<(32767+1 == -32768) is false so the loop ends. But many OSs produces a fault when a overflow occurs.
So there is no performance difference ?
Couldn't be answered for general. You don't know what your compiler does during optimization.
Right, now that we know about command line arguments, what's theproblem again??