Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • World
  • Users
  • Groups
Skins
  • Light
  • Cerulean
  • Cosmo
  • Flatly
  • Journal
  • Litera
  • Lumen
  • Lux
  • Materia
  • Minty
  • Morph
  • Pulse
  • Sandstone
  • Simplex
  • Sketchy
  • Spacelab
  • United
  • Yeti
  • Zephyr
  • Dark
  • Cyborg
  • Darkly
  • Quartz
  • Slate
  • Solar
  • Superhero
  • Vapor

  • Default (No Skin)
  • No Skin
Collapse
Code Project
CODE PROJECT For Those Who Code
  • Home
  • Articles
  • FAQ
Community
  1. Home
  2. General Programming
  3. C / C++ / MFC
  4. static variable

static variable

Scheduled Pinned Locked Moved C / C++ / MFC
c++question
39 Posts 8 Posters 0 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • G George_George

    Thanks Josh, I can understand and agree that your approach works. But when we come back to my approach, returning address of function *local* static variable, are there any disadvantages? regards, George

    G Offline
    G Offline
    ghle
    wrote on last edited by
    #30

    Personal experience says your approach will not work. Inaccessible address, I think. Depends on compiler, I guess. Maybe exception error at run time... IIRC we are talking heap versus stack issues.

    1 Reply Last reply
    0
    • G George_George

      Thanks Josh, I can understand and agree that your approach works. But when we come back to my approach, returning address of function *local* static variable, are there any disadvantages? regards, George

      G Offline
      G Offline
      ghle
      wrote on last edited by
      #31

      (Surprised) I tried it and it worked. There was no problem accessing the static variable by address outside the function. Be certain not to in-line the function, as that has certain ramifications. The static is created on the heap, and the address *is* accessible from outside the class and outside the function it is defined in. I am quite surprised. I thought even the compiler would catch it. Ignore previous post.:-O int *CPBDialog::TryThis() { static int test; test += 1; return &test; } CErrorOkDlg::CErrorOkDlg(CWnd* pParent /*=NULL*/) : CPBDialog(CErrorOkDlg::IDD, pParent) { //{{AFX_DATA_INIT(CErrorOkDlg) //}}AFX_DATA_INIT } BOOL CErrorOkDlg::OnInitDialog() { CPBDialog::OnInitDialog(); ModifyStyleEx(0,WS_EX_NODRAG,0); // Sound Beeper SoundWarning(); int *test = TryThis(); int test2 = *test; return FALSE; } Gary

      G 1 Reply Last reply
      0
      • T toxcct

        do you know what thread safe means ? can't you search the web before asking dumb questions like you know doing very well, and weighting the forum for nothing ? returning the address of a local static variable isn't thread safe simply means that if a thread is calling the function (so, potentially being modifying the variable value), but another thread is modifying the variable at the same time, using the direct access through its address, you cannot ensure of the final value of the variable... when both threads write at the same place at the same time, the one which wrote the memory at last wins the game... ps: so i see you keep playing with the voting system... be very careful when voting my posts. they can just explode on you face, but then don't ever wonder why :p


        [VisualCalc][Binary Guide][CommDialogs] | [Forums Guidelines]

        G Offline
        G Offline
        George_George
        wrote on last edited by
        #32

        Thanks toxcct, Your answer is clear. regards, George

        1 Reply Last reply
        0
        • C codeII

          int& MyFunction( ) { static int localStatic = 0; int nMyArray[ 10 ]; if ( localStatic < 10 ) { //localStatic is not guaranteed < 10 nMyArray[ localStatic ] = 1; } return localStatic; } When one tread comes inside the “if statement” another tread could have set localStatic to for instance 11. If you want to use a variable outside the scope of the function why are you not using a global? When using a static in a function this “means” that the function is responsible for this variable. And it cannot, when this variable is managed outside this function. Keeping strict rules provides confusing situations, In terms of who is modifying what. Another thing you should know is that when you are using a static within a class function, different instances of this class would use the same static instance; this can cause problems like the tread example above. Using globals: In header: extern int g_MyVar; In cpp int g_MyVar = 0; or when possible using a local variable giving to the function void MyFunction( int& nValue ) { nValue++; … } int nValue = 0; MyFunction( nValue );

          G Offline
          G Offline
          George_George
          wrote on last edited by
          #33

          Thanks koos, Your answer is great! regards, George

          1 Reply Last reply
          0
          • D David Crow

            George_George wrote:

            I am wondering how C or C++ manages static variable internally.

            I believe it's in the data segment.


            "A good athlete is the result of a good and worthy opponent." - David Crow

            "To have a respect for ourselves guides our morals; to have deference for others governs our manners." - Laurence Sterne

            G Offline
            G Offline
            George_George
            wrote on last edited by
            #34

            Thanks DavidCrow, Data segment is some global space of a process, compared with function local stack space? regards, George

            1 Reply Last reply
            0
            • G ghle

              (Surprised) I tried it and it worked. There was no problem accessing the static variable by address outside the function. Be certain not to in-line the function, as that has certain ramifications. The static is created on the heap, and the address *is* accessible from outside the class and outside the function it is defined in. I am quite surprised. I thought even the compiler would catch it. Ignore previous post.:-O int *CPBDialog::TryThis() { static int test; test += 1; return &test; } CErrorOkDlg::CErrorOkDlg(CWnd* pParent /*=NULL*/) : CPBDialog(CErrorOkDlg::IDD, pParent) { //{{AFX_DATA_INIT(CErrorOkDlg) //}}AFX_DATA_INIT } BOOL CErrorOkDlg::OnInitDialog() { CPBDialog::OnInitDialog(); ModifyStyleEx(0,WS_EX_NODRAG,0); // Sound Beeper SoundWarning(); int *test = TryThis(); int test2 = *test; return FALSE; } Gary

              G Offline
              G Offline
              George_George
              wrote on last edited by
              #35

              Thanks for your help and sample, Gary! It is great! regards, George

              1 Reply Last reply
              0
              • G George_George

                Hello everyone, I am wondering how C or C++ manages static variable internally. Since each time when we again a function again, if in this function, a static variable is defined, the value will be the value last time when we entered this function (i.e. will not be initialized again, and only initialized at the 1st time). I suspect it is stored in some global structure to reserve the value? thanks in advance, George

                G Offline
                G Offline
                ghle
                wrote on last edited by
                #36

                George_George wrote:

                I am wondering how C or C++ manages static variable internally.

                Global statics are placed on the heap, not the stack. They are initialized upon first use by the application. They are destroyed upon exit from the application. Whereas variables on the stack come and go, the heap hangs around until program termination. I had thought Global statics were handled differently than Local statics, but I proved myself wrong. Beware of INLINE statics, however. If the code is actually INLINED, the compiler may create multiple instances of the static variable storage, plus one that is global. This will no doubt lead to problems. Gary

                G 1 Reply Last reply
                0
                • G ghle

                  George_George wrote:

                  I am wondering how C or C++ manages static variable internally.

                  Global statics are placed on the heap, not the stack. They are initialized upon first use by the application. They are destroyed upon exit from the application. Whereas variables on the stack come and go, the heap hangs around until program termination. I had thought Global statics were handled differently than Local statics, but I proved myself wrong. Beware of INLINE statics, however. If the code is actually INLINED, the compiler may create multiple instances of the static variable storage, plus one that is global. This will no doubt lead to problems. Gary

                  G Offline
                  G Offline
                  George_George
                  wrote on last edited by
                  #37

                  Thanks Gary,

                  ghle wrote:

                  I had thought Global statics were handled differently than Local statics, but I proved myself wrong.

                  You mean global static variable and function local variable are handled in the same way by compiler? regards, George

                  G 1 Reply Last reply
                  0
                  • G George_George

                    Thanks Gary,

                    ghle wrote:

                    I had thought Global statics were handled differently than Local statics, but I proved myself wrong.

                    You mean global static variable and function local variable are handled in the same way by compiler? regards, George

                    G Offline
                    G Offline
                    ghle
                    wrote on last edited by
                    #38

                    George_George wrote:

                    You mean global static variable and function local variable are handled in the same way by compiler?

                    George, both the global statics and local statics are placed onto the heap - by the compiler. I'd say they are handled similar, but not identical. For example, global statics are initialized at start-up of the program, but local statics are not initialized until they first come into scope. Both are destroyed only upon termination of the program, that is when the heap is destroyed. You said "function local variable", but I mean function local STATIC variable. A function local variable - non-static - are pushed onto the stack not put in the heap. When the function goes out of scope, so do it's variables. Returning from the function to the calling program will pop the stack, removing all local non-static variables from existence. But the function static variables were put on the heap, and they still exist after the function goes out of scope, available to the routine/method once it comes back into scope from another call. (And as noted earlier in this thread, I found local statics were available from outside of the local function if the address of the static is returned by the method.)

                    Heap
                    Global statics
                    Main() statics
                    Method B statics
                    Method C statics
                    /Heap

                    **Stack after calling Main()** _Main() non-static variables_ **/Stack** **Stack after calling method B from Main()** _Main() non-static variables Method B non-static variables_ **/Stack** **Stack after calling method C from B** _Main() non-static variables Method B non-static variables Method C non-static variables_ **/Stack** **Stack after calling method C from method C (recursion)** _Main() non-static variables Method B non-static variables Method C non-static variables Susequent method C non-static variables_ **/Stack** **Stack after returning from method C to method B** _Main() non-static variables Method B non-static variables_ **/Stack** **Stack after returning to Main() from method B** _Main() non-static variables_ **/Stack**

                    Heap after returning to Main(). All statics now initialized.
                    Global statics
                    Main() statics
                    Method B statics
                    Method C statics
                    /Heap

                    Gary -- modified at 8:43 Monday 27th August, 2007

                    G 1 Reply Last reply
                    0
                    • G ghle

                      George_George wrote:

                      You mean global static variable and function local variable are handled in the same way by compiler?

                      George, both the global statics and local statics are placed onto the heap - by the compiler. I'd say they are handled similar, but not identical. For example, global statics are initialized at start-up of the program, but local statics are not initialized until they first come into scope. Both are destroyed only upon termination of the program, that is when the heap is destroyed. You said "function local variable", but I mean function local STATIC variable. A function local variable - non-static - are pushed onto the stack not put in the heap. When the function goes out of scope, so do it's variables. Returning from the function to the calling program will pop the stack, removing all local non-static variables from existence. But the function static variables were put on the heap, and they still exist after the function goes out of scope, available to the routine/method once it comes back into scope from another call. (And as noted earlier in this thread, I found local statics were available from outside of the local function if the address of the static is returned by the method.)

                      Heap
                      Global statics
                      Main() statics
                      Method B statics
                      Method C statics
                      /Heap

                      **Stack after calling Main()** _Main() non-static variables_ **/Stack** **Stack after calling method B from Main()** _Main() non-static variables Method B non-static variables_ **/Stack** **Stack after calling method C from B** _Main() non-static variables Method B non-static variables Method C non-static variables_ **/Stack** **Stack after calling method C from method C (recursion)** _Main() non-static variables Method B non-static variables Method C non-static variables Susequent method C non-static variables_ **/Stack** **Stack after returning from method C to method B** _Main() non-static variables Method B non-static variables_ **/Stack** **Stack after returning to Main() from method B** _Main() non-static variables_ **/Stack**

                      Heap after returning to Main(). All statics now initialized.
                      Global statics
                      Main() statics
                      Method B statics
                      Method C statics
                      /Heap

                      Gary -- modified at 8:43 Monday 27th August, 2007

                      G Offline
                      G Offline
                      George_George
                      wrote on last edited by
                      #39

                      Thanks Gary, Your reply is great! regards, George

                      1 Reply Last reply
                      0
                      Reply
                      • Reply as topic
                      Log in to reply
                      • Oldest to Newest
                      • Newest to Oldest
                      • Most Votes


                      • Login

                      • Don't have an account? Register

                      • Login or register to search.
                      • First post
                        Last post
                      0
                      • Categories
                      • Recent
                      • Tags
                      • Popular
                      • World
                      • Users
                      • Groups