Thread: definition inside block

  1. #1
    Registered User PutoAmo's Avatar
    Join Date
    Mar 2002
    Posts
    72

    definition inside block

    Hi

    I have seen several programs that define variables inside a block, like:

    Code:
    int main (void)
    {
       ...
       ...
       ...
       while (...)
       {
           int variable;
           ...
           ...
       }
       ...
       ...
    }
    Are there any advantages in using such code?

    Thx !

  2. #2
    Off the top of my head I can't think of any advantages.

    As for disadvantages:

    The scope of variable is only within the whlie loop. so if another function needed to use it, it wouldn't have access to it.
    DrakkenKorin

    Get off my Intarweb!!!!

  3. #3
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >The scope of variable is only within the whlie loop. so if another
    >function needed to use it, it wouldn't have access to it
    That's also one of the advantages. Another disadvantage is that the memory for that variable is allocated and freed with every iteration of the loop, often causing a performance drop. Generally, you only need to create variables at the top of a function if the function was written properly.

    -Prelude
    My best code is written with the delete key.

  4. #4
    Registered User PutoAmo's Avatar
    Join Date
    Mar 2002
    Posts
    72

    Thumbs up

    GRACIAS.

  5. #5
    Originally posted by Prelude
    >The scope of variable is only within the whlie loop. so if another
    >function needed to use it, it wouldn't have access to it
    That's also one of the advantages. Another disadvantage is that the memory for that variable is allocated and freed with every iteration of the loop, often causing a performance drop. Generally, you only need to create variables at the top of a function if the function was written properly.

    -Prelude
    You know, Prelude,

    I really wished you were one of my instructors at school becuase what I posted was the def. we were taught for scope.

    I'll pay you $.05 a day for tutoring!
    DrakkenKorin

    Get off my Intarweb!!!!

  6. #6
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    This is really C++ but it kinda falls withing the same scope*smile*

    Code:
    void f()
    {
        for(int i = 0; i < 5; i++)
        {
            something();
        }
    
        for(int i = 0; i < 5; i++)
        {
            something_else();
        }
    }
    This will generate an error because in this case i is not local to the for loop.
    Last edited by Barjor; 04-18-2002 at 02:17 PM.

  7. #7
    ATH0 quzah's Avatar
    Join Date
    Oct 2001
    Posts
    14,826
    Originally posted by Barjor
    This is really C++ but it kinda falls withing the same scope*smile*

    Code:
    void f()
    {
        for(int i = 0; i < 5; i++)
        {
            something();
        }
    
        for(int i = 0; i < 5; i++)
        {
            something_else();
        }
    }
    This will generate an error because in this case i is not local to the for loop.

    What? That is legal C++ code. The reason it doesn't work in C is that C doesn't allow variable declarations in the middle of the scope. For example:
    Code:
    /*C*/
    int main( void )
    {
        printf("Hello.\n");
        int x; /* invalid this has to go before the printf */
    
        {
            int y; /* valid; this happens first in the scope */
            printf("Wheee...");
        }
        return x;
    }
    
    
    //C++
    int main( void )
    {
        cout << "Hello" << endl;
        int x; // Valid. C++ Allows variable declaration almost anywhere.
    
        {
            int y; // valid; this happens first in the scope
            printf("Wheee...");
        }
    
        return x; //return some random undefined value to the OS...
    }
    That is the difference between C++ and C regarding variable declarations in a given scope.

    Quzah.
    Hope is the first step on the road to disappointment.

  8. #8
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    No it's not valid C++. In my compiler it says redefenition of i. My point is that i is not local to the for loop
    Last edited by Barjor; 04-18-2002 at 02:52 PM.

  9. #9
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    > Another disadvantage is that the memory for that variable is allocated and freed with every iteration of the loop
    Doesn't seem to be true all the time - tried it with GCC, and all the variable space is allocated at the start of the function. Scope in this case is enforced at compile time, not run time.

    If on the other hand, it was a C++ object with a constructor/destructor, then I can well imagine that some extra work would be performed on each iteration.

    > This will generate an error because in this case i is not local to the for loop
    This is true of the old C++ standard, but not the new C++ standard. The new standard specifically makes such declarations exist just for the loop itself, not the rest of the block.

  10. #10
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    Originally posted by Salem
    > This will generate an error because in this case i is not local to the for loop
    This is true of the old C++ standard, but not the new C++ standard. The new standard specifically makes such declarations exist just for the loop itself, not the rest of the block.
    Now when you say it. I kinda remeber reading something that VC++ didn't follow the standard about for loops. Anyone know if this is fixed in VC.NET? How about this?

    Code:
    for(int i = 0; i < 5; i++)
    {
        for(int i = 0; i < 5; i++)
        {
              i++;//will this change the second i but not the first?
        }
    }
    Or will that not even compile?
    Last edited by Barjor; 04-18-2002 at 03:29 PM.

  11. #11
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    This code compiled in VC 6.0 sp5
    Code:
    #include <iostream.h>
    
    int main()
    {
    	for(int i = 0; i < 3; i++)
    	{
    			for(int i = 0; i < 3; i++)
    			{
    				cout<<"Inner"<<i<<"\n";
    			}
    
    		cout<<"Outer"<<i<<"\n";
    	}
    
    	return 0;
    }
    gives me this output
    Code:
    Inner0
    Inner1
    Inner2
    Outer3
    Inner0
    Inner1
    Inner2
    Outer3
    Inner0
    Inner1
    Inner2
    Outer3
    So how come the outer loop runs three times when the outer i is 3 and really should break the outer loop?
    If I do it this way
    Code:
    #include <iostream.h>
    
    int main()
    {
    	for(int i = 0; i < 3; i++)
    	{
    		cout<<"Outer"<<i<<"\n";
    
    		for(int i = 0; i < 3; i++)
    		{
    			cout<<"Inner"<<i<<"\n";
    		}
    	}
    
    	return 0;
    }
    I get this output
    Code:
    Outer0
    Inner0
    Inner1
    Inner2
    Outer1
    Inner0
    Inner1
    Inner2
    Outer2
    Inner0
    Inner1
    Inner2
    This is more in line with what I would expect. It looks like the inner i's scope is "leaking" on my first piece of code

    If I compile my first code in K-Develop it gives me these varnings
    Code:
    name lookup of 'i' changed
    matches this 'i' under ISO standard rules
    matches this 'i' under old rules
    and my output is
    Code:
    Inner0
    Inner1
    Inner2
    Outer0
    Inner0
    Inner1
    Inner2
    Outer1
    Inner0
    Inner1
    Inner2
    Outer2
    As it should
    So I guess you where right Quazah and Salem and I and MS where wrong
    Last edited by Barjor; 04-18-2002 at 11:17 PM.

  12. #12
    and the hat of int overfl Salem's Avatar
    Join Date
    Aug 2001
    Location
    The edge of the known universe
    Posts
    39,659
    Code:
    #include <iostream.h>
    
    int main() {
        for ( int i = 0; i < 3; i++) {
            for ( int i = 0; i < 3; i++) {
                cout<<"Inner"<<i<<"\n";
            }
            cout<<"Outer"<<i<<"\n";
        }
        return 0;
    }
    There are 3 different ways to compile this with gcc (3.03), and 2 different sets of results
    D:\code>gxx scope.cpp
    scope.cpp: In function `int main()':
    scope.cpp:8: warning: name lookup of `i' changed
    scope.cpp:4: warning: matches this `i' under ISO standard rules
    scope.cpp:5: warning: matches this `i' under old rules

    D:\code>a.exe
    Inner0
    Inner1
    Inner2
    Outer0
    Inner0
    Inner1
    Inner2
    Outer1
    Inner0
    Inner1
    Inner2
    Outer2

    D:\code>gxx -ffor-scope scope.cpp

    D:\code>a.exe
    Inner0
    Inner1
    Inner2
    Outer0
    Inner0
    Inner1
    Inner2
    Outer1
    Inner0
    Inner1
    Inner2
    Outer2

    D:\code>gxx -fno-for-scope scope.cpp

    D:\code>a.exe
    Inner0
    Inner1
    Inner2
    Outer3
    Inner0
    Inner1
    Inner2
    Outer3
    Inner0
    Inner1
    Inner2
    Outer3

    This is what the manual page says
    If -ffor-scope is specified, the scope of variables declared in a for-init-statement is limited to the for loop itself, as specified by the draft C++ standard. If -fno-for-scope is specified, the scope of variables declared in a for-init-statement extends to the end of the enclosing scope, as was the case in old versions of gcc, and other (traditional) implementations of C++.
    The default if neither flag is given to follow the standard, but to allow and give a warning for old-style code that would otherwise be invalid, or have different behavior.

    > This is more in line with what I would expect. It looks like the inner i's scope is "leaking" on my first piece of code
    No, the scope of the inner i is just extending its scope to the end of the enclosing block.

    > So how come the outer loop runs three times when the outer i is 3 and really should break the outer loop
    It's down to the finer points of where scope begins and ends. I imagine that the scope of the inner i ends just before the }, and the scope of the outer i resumes just after the }

    > As it should
    You're comparing your old standard compiler with your new standard compiler.

  13. #13
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,897
    >Doesn't seem to be true all the time - tried it with GCC, and all
    >the variable space is allocated at the start of the function.
    >Scope in this case is enforced at compile time, not run time.
    Agreed, I ran a test on MSVC in debug mode and the space was reallocated with each iteration. So either the result will be different with each implementation or it would only show up when the compiler makes no optimizations.

    -Prelude
    My best code is written with the delete key.

  14. #14
    Registered User
    Join Date
    Feb 2002
    Posts
    589
    <<You're comparing your old standard compiler with your new standard compiler.>>

    Yeah. I would expect that VC++ 6.0 sp5 would conform to the new standard but it doesn't look like it. O well. I learn something new every day.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Dikumud
    By maxorator in forum C++ Programming
    Replies: 1
    Last Post: 10-01-2005, 06:39 AM
  2. HUGE fps jump
    By DavidP in forum Game Programming
    Replies: 23
    Last Post: 07-01-2004, 10:36 AM
  3. Warnings, warnings, warnings?
    By spentdome in forum C Programming
    Replies: 25
    Last Post: 05-27-2002, 06:49 PM
  4. gcc problem
    By bjdea1 in forum Linux Programming
    Replies: 13
    Last Post: 04-29-2002, 06:51 PM
  5. Header files
    By borland_man in forum C++ Programming
    Replies: 14
    Last Post: 02-22-2002, 04:30 AM