Thread: Local stacks, curly braces

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

    Local stacks, curly braces

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

    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?
    Microsoft Visual Studio .NET 2003 Enterprise Architect
    Windows XP Pro

    Code Tags
    Programming FAQ

  2. #2
    Banned master5001's Avatar
    Join Date
    Aug 2001
    Visalia, CA, USA
    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
    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:

    #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, 03: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
    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, 09:32 AM