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.
  • L Lost User

    George_George wrote:

    I think you mean static member of a class. But I mean a static variable defined inside a function.

    Yes you are right which makes me wonder why you have global methods? I suspect there is probably a better to solution to what you are trying to do but its hard to suggest anything without knowing more about what you are doing and in what context

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

    Thanks Josh, You are right. I am writing a part of the application in C (not C++). I am wondering and willing to listen to your comments and ideas of any disadvantages if I return the address of static variable defined in a function, then let other part of code to access the variable by the returned address. regards, George

    L 1 Reply Last reply
    0
    • G George_George

      Thanks Josh, You are right. I am writing a part of the application in C (not C++). I am wondering and willing to listen to your comments and ideas of any disadvantages if I return the address of static variable defined in a function, then let other part of code to access the variable by the returned address. regards, George

      L Offline
      L Offline
      Lost User
      wrote on last edited by
      #19

      George_George wrote:

      You are right. I am writing a part of the application in C (not C++). I am wondering and willing to listen to your comments and ideas of any disadvantages if I return the address of static variable defined in a function, then let other part of code to access the variable by the returned address.

      Well you could make the static global rather than defining it within a function then have two function to get and set its value but thats just an attempt to make a procedural language more OO.

      G 1 Reply Last reply
      0
      • T ThatsAlok

        George_George wrote:

        How do you think returning static variable is similar to Singleton pattern

        just on basic.. concept of Singleton pattern says that.. there should only copy exist for any variable.. look more in detail here:- http://www.codeproject.com/cpp/singletonrvs.asp[^]

        "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
        Never mind - my own stupidity is the source of every "problem" - Mixture

        cheers, Alok Gupta VC Forum Q&A :- I/IV Support CRY- Child Relief and You

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

        Thanks Alok, The similarity you mean is only one copy of data? regards, George

        T 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

          B Offline
          B Offline
          BadKarma
          wrote on last edited by
          #21

          This is a very interresting article about the use and the concept of the static keyword clickety[^]

          codito ergo sum

          G 1 Reply Last reply
          0
          • L Lost User

            George_George wrote:

            You are right. I am writing a part of the application in C (not C++). I am wondering and willing to listen to your comments and ideas of any disadvantages if I return the address of static variable defined in a function, then let other part of code to access the variable by the returned address.

            Well you could make the static global rather than defining it within a function then have two function to get and set its value but thats just an attempt to make a procedural language more OO.

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

            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 2 Replies Last reply
            0
            • B BadKarma

              This is a very interresting article about the use and the concept of the static keyword clickety[^]

              codito ergo sum

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

              Thanks BadKarma, If I mean local static function variable, and if I use the address of the variable as the return value, then access the address outside the function (read/write). Does this approach have any disadvantages? regards, George

              B 1 Reply Last reply
              0
              • G George_George

                Thanks BadKarma, If I mean local static function variable, and if I use the address of the variable as the return value, then access the address outside the function (read/write). Does this approach have any disadvantages? regards, George

                B Offline
                B Offline
                BadKarma
                wrote on last edited by
                #24

                Whether this is a bad design or a good one, depends on the place where you use this. So you should think carefully where to implement. There is however on big disadvantage to this design. The function isn't thread safe. This means that when called from multiple threads the behavior will be unpredictable.

                codito ergo sum

                G 1 Reply Last reply
                0
                • B BadKarma

                  Whether this is a bad design or a good one, depends on the place where you use this. So you should think carefully where to implement. There is however on big disadvantage to this design. The function isn't thread safe. This means that when called from multiple threads the behavior will be unpredictable.

                  codito ergo sum

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

                  Thanks BadKarma,

                  BadKarma wrote:

                  This means that when called from multiple threads the behavior will be unpredictable

                  Could you provide more detailed scenario to describe why it is not thread safe please? regards, George

                  T C 2 Replies Last reply
                  0
                  • G George_George

                    Thanks BadKarma,

                    BadKarma wrote:

                    This means that when called from multiple threads the behavior will be unpredictable

                    Could you provide more detailed scenario to describe why it is not thread safe please? regards, George

                    T Offline
                    T Offline
                    toxcct
                    wrote on last edited by
                    #26

                    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 1 Reply Last reply
                    0
                    • G George_George

                      Thanks BadKarma,

                      BadKarma wrote:

                      This means that when called from multiple threads the behavior will be unpredictable

                      Could you provide more detailed scenario to describe why it is not thread safe please? regards, George

                      C Offline
                      C Offline
                      codeII
                      wrote on last edited by
                      #27

                      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 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

                        D Offline
                        D Offline
                        David Crow
                        wrote on last edited by
                        #28

                        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 1 Reply Last reply
                        0
                        • G George_George

                          Thanks Alok, The similarity you mean is only one copy of data? regards, George

                          T Offline
                          T Offline
                          ThatsAlok
                          wrote on last edited by
                          #29

                          thats what single pattern all about

                          "Opinions are neither right nor wrong. I cannot change your opinion. I can, however, change what influences your opinion." - David Crow
                          Never mind - my own stupidity is the source of every "problem" - Mixture

                          cheers, Alok Gupta VC Forum Q&A :- I/IV Support CRY- Child Relief and You

                          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
                            #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
                                          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