Thread: Definition in LOOP Block

  1. #1
    Registered User
    Join Date
    Nov 2019
    Posts
    13

    Definition in LOOP Block

    Hi,
    I'm totally confused when I want to define parameter inside loop like this
    Code:
    for (int i=0; i<25;i++)
    {
        int j=0;
        j++;
    }
    So we know that once we define a variable as the compiler link to it specific address, my question is about variable j in my case, will the compiler relate to it as new variable at every iteration? I mean :
    first iteration j=0; j++
    second iteration j will still j=0; j++
    third iteration j will still j=0; j++
    etc ...

    does the compiler at every iteration will define j again and initialize it again with 0 at every iteration?

    what's confusing me is how the pc/compiler will deal with defining variable that are inside the loop's block that we are looping again and again on the same loop's block(for or while loops doesn't matter)?
    Last edited by Brian_Teir; 12-06-2019 at 11:00 AM.

  2. #2
    Registered User
    Join Date
    May 2009
    Posts
    3,729
    The compiler will likely remove all of the "j" code because it does nothing useful from its view point.

    Tim S.
    "...a computer is a stupid machine with the ability to do incredibly smart things, while computer programmers are smart people with the ability to do incredibly stupid things. They are,in short, a perfect match.." Bill Bryson

  3. #3
    Registered User
    Join Date
    Dec 2017
    Posts
    788
    does the compiler at every iteration will define j again and initialize it again with 0 at every iteration?
    The compiler acts as if it redefines the variable every loop iteration, but it doesn't necessarily do it that way. At a high enough optimization level, it will probably notice that the entire loop does absolutely nothing and elimiate the whole thing. Even if you added a printf to print the value of j every time, the optimizer would probably notice that it always prints 1 and again remove j and just print 1. Or if you added an accumulating variable summing the value of i every iteration and printing it after the loop, it would probably notice that the sum would always be 25 and just print 25.
    The world hangs on a thin thread, and that is the psyche of man. - Carl Jung

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Loop Unrolling/Block Copy
    By memcpy in forum C Programming
    Replies: 6
    Last Post: 03-22-2012, 11:24 PM
  2. Replies: 3
    Last Post: 12-13-2011, 07:32 AM
  3. Loop a block of code
    By Axiom in forum C Programming
    Replies: 2
    Last Post: 11-23-2008, 11:33 PM
  4. definition inside block
    By PutoAmo in forum C Programming
    Replies: 13
    Last Post: 04-19-2002, 09:20 AM

Tags for this Thread