Local stacks, curly braces

This is a discussion on Local stacks, curly braces within the C++ Programming forums, part of the General Programming Boards category; If you place curly braces within a function, does that create a new sub-stack? Eg: Code: int main() { int ...

  1. #1
    mustang benny bennyandthejets's Avatar
    Join Date
    Jul 2002
    Posts
    1,401

    Local stacks, curly braces

    If you place curly braces within a function, does that create a new sub-stack? Eg:

    Code:
    int main()
    {
        int x;
        {
            int y;
        }
        return 0;
    }
    Is y in a sub-stack of the one that x is in? That would seem logical, given the behavior of the variables. Ie, x is available everywhere, but y is only available within the nested braces.

    Am I on the right track here?
    benforbes@optusnet.com.au
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ
    Tutorials

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Location
    Visalia, CA, USA
    Posts
    3,685
    As far as I know scoping rules do not suggest a sub-stack. Just because in your example y can only be used in the inner most set of {}'s does not mean that it is in a different stack.

  3. #3
    Registered User
    Join Date
    May 2003
    Posts
    161
    While there is no "sub-stack", scoping can have an effect on the stack. After a variable goes out of scope, the compiler is allowed to use that variable's stack space for variables that are declared later on.

    For example:

    Code:
    #include <iostream>
    
    using namespace std;
    
    int main()
    {
    
      {
        int y = 10;
      }
    
      int x;
    
      cout << x << endl;
    
      return 0;
    }
    My output from this program is 10 even though I never initialize x. The compiler is using y's stack space for x because y will never be in scope again.

    Note that you shouldn't depend on this behavior. It may vary depending on which compiler you use and the level of optimization.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. is curly braces here is a must?
    By mashour06 in forum C Programming
    Replies: 8
    Last Post: 04-25-2009, 04:41 PM
  2. error: braces around scalar initializer...
    By Osiris990 in forum C++ Programming
    Replies: 2
    Last Post: 02-27-2008, 02:22 PM
  3. Screwy Linker Error - VC2005
    By Tonto in forum C++ Programming
    Replies: 5
    Last Post: 06-19-2007, 02:39 PM
  4. Folding@Home Cboard team?
    By jverkoey in forum A Brief History of Cprogramming.com
    Replies: 398
    Last Post: 10-11-2005, 08:44 AM
  5. pointers
    By InvariantLoop in forum C Programming
    Replies: 13
    Last Post: 02-04-2005, 08:32 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21