Re: statics/globals

Discussion in 'C++' started by tom_usenet, Jun 15, 2004.

  1. tom_usenet

    tom_usenet Guest

    On Mon, 14 Jun 2004 18:57:16 -0400, bala <> wrote:

    >I've a static variable in a file which is used by a function foo()
    >within that file. A static variable from another file calls foo() to
    >initialize itself. Since the order of initialization of these variables
    >(across compilation units) are not guaranteed, the results are
    >undefined. Here is what I have:
    >//File A.C
    >#include <string>
    >static std:: string abc("SampleString");
    >std:: string foo(std:: string const& s) { return s + abc; }
    >std:: string prefix(std:: string const& s) { return abc + s; }
    >// File main.C
    >#include <iostream>
    >#include <string>
    >std:: string foo(std:: string const& s);
    >static std:: string s = foo("S-");
    >int main() { std:: cout << "s = " << s << std::endl; }
    >
    >g++ main.C A.C
    >
    >It seems simple enough for the compiler to see that a local static
    >variable is used within an external function.


    There's nothing wrong with that, as long as the function isn't called
    during initialization of any other globals. Spurious warnings are a
    pain in the neck at the best of times. In effect, every function that
    accesses a global variable must generate the warning...

    So the compiler can warn
    >against such usage--gcc doesn't even under -Wall. The compiler can also
    >(if forced by the standard) automatically initialize the static variable
    >'abc' when foo() is called for the first time.


    But that might involve the compiler inserting extra code in every
    function that accesses a global variable, just in case it is called
    during program startup. Sounds like Java style safety to me (e.g.
    safety at the expense of performance).

    Tom
    --
    C++ FAQ: http://www.parashift.com/c -faq-lite/
    C FAQ: http://www.eskimo.com/~scs/C-faq/top.html
    tom_usenet, Jun 15, 2004
    #1
    1. Advertising

Want to reply to this thread or ask your own question?

It takes just 2 minutes to sign up (and it's free!). Just click the sign up button to choose a username and then you can ask your own questions on the forum.
Similar Threads
  1. Jason

    Statics and connections

    Jason, Dec 6, 2004, in forum: ASP .Net
    Replies:
    2
    Views:
    1,730
    Jason
    Dec 6, 2004
  2. Roedy Green

    statics in inner classes

    Roedy Green, Jul 1, 2005, in forum: Java
    Replies:
    14
    Views:
    734
    Thomas G. Marshall
    Jul 12, 2005
  3. Roedy Green

    initialising statics

    Roedy Green, Jan 22, 2006, in forum: Java
    Replies:
    8
    Views:
    600
    John C. Bollinger
    Jan 27, 2006
  4. Andrey
    Replies:
    6
    Views:
    365
    Andrew Koenig
    Jun 24, 2004
  5. Stuart MacMartin
    Replies:
    5
    Views:
    550
    Victor Bazarov
    Jul 27, 2005
Loading...

Share This Page