473,405 Members | 2,444 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,405 software developers and data experts.

Static function-vars and the compiler

I'd like to know how compilers usually handle static variables that
are declared inside a function (as opposed to static class-members).
Like in:

int counter(){
static int c=0;
++c;
return c;
}

I would assume the compiler changes it into something like this:

bool counter_c_is_initialized = false;
int counter_c;
int counter(){
if (!counter_c_is_initialized){
c = 0;
counter_c_is_initialized = true;
}
++c;
return c;
}

Since they do not seem to be initialized when the function is never
called. Am i correct here? So if this is correct there will be an
extra conditional every time the function is called.

I've lately taken to implementing singletons with a static function
var, something like this:

class Singleton{
public:
static Singleton& get(){
static Singleton single;
return single;
}
private:
Singleton(){}
};

This only works if the constructor does not take arguments, but it
does take care of the destruction of the object when the program
terminates. Any problems with this form of singleons? I guess i do not
have precise control over the order in which such objects get
destructed, so if the destructor depends on another semi-global object
it could cause problems.

Marijn Haverbeke
Jul 19 '05 #1
5 2729
"Marijn" <ma******@hotmail.com> wrote in message
news:1d**************************@posting.google.c om...
I'd like to know how compilers usually handle static variables that
are declared inside a function (as opposed to static class-members).
Like in:

int counter(){
static int c=0;
++c;
return c;
}

I would assume the compiler changes it into something like this:

bool counter_c_is_initialized = false;
int counter_c;
int counter(){
if (!counter_c_is_initialized){
c = 0;
counter_c_is_initialized = true;
}
++c;
return c;
}

Since they do not seem to be initialized when the function is never
called. Am i correct here?
Some time ago I digged into the assembly output of the Borland C++
Builder compiler. This compiler deals with static objects declared
inside a function exactly the way you described. Unfortunately this
solution is not multi-thread safe. I didn't check this with other
compilers, and the standard dictates only that static objects are only
initialized once, not how compilers should solve this problem. I.e. your
mileage may vary.
So if this is correct there will be an
extra conditional every time the function is called.
It is plausible that something like that will take place, though in
theory the compiler may resort to self modifying code as well.
I've lately taken to implementing singletons with a static function
var, something like this:

class Singleton{
public:
static Singleton& get(){
static Singleton single;
return single;
}
private:
Singleton(){}
};

This only works if the constructor does not take arguments, but it
does take care of the destruction of the object when the program
terminates. Any problems with this form of singleons? I guess i do not
have precise control over the order in which such objects get
destructed, so if the destructor depends on another semi-global object
it could cause problems.


You are correct; only the order of destruction within a translation unit
(.cpp file) is guaranteed. The book "Modern C++ Design" from Andrei
Alexandrescu does discusses techniques to deal with this problem.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl
Jul 19 '05 #2
> It is plausible that something like that will take place, though in
theory the compiler may resort to self modifying code as well.


Self-modifying code? Wow, sounds weird. Do any compilers actually do
that? That would make this static-variable-initialization much more
efficient though. I'll try to decipher the assembly that G++ spits
out. (My assembly reading skills are quite lousy.)

Marijn
Jul 19 '05 #3
"Marijn" <ma******@hotmail.com> wrote in message
news:1d**************************@posting.google.c om...
It is plausible that something like that will take place, though in
theory the compiler may resort to self modifying code as well.
Self-modifying code? Wow, sounds weird. Do any compilers actually do
that?


Not any that I know of. And I don't think many will since self-modifying
code is in most cases a bad idea. I just mentioned it to make it clear that
compilers do not have to follow the method you described. But I expect many
compilers do the check with an additional helper variable for static objects
with non-trivial constructors.

Note that for primitive types like 'int' the compiler may also (and probably
will) use initialized memory, which is set to the initial value of the
static variable. That way no initialization check is needed when the
function is entered.
That would make this static-variable-initialization much more
efficient though.
static variable initialization is usually not a real performance concern.
I'll try to decipher the assembly that G++ spits
out. (My assembly reading skills are quite lousy.)


That can be an interesting excercise. Combined with common sense it can
provide you with valuable insights about the optimization capabilities of
the compiler. One of the most important lessons to be learned is probably
that many of those "clever" & dirty optimization tricks some people are
eager to use have little or no effect on the efficiency. Some of them are
even detrimental. An excellent example is the "integer divide by 7 trick?"
thread of a week ago. Any halfway decent compiler will generate the optimal
code sequence to do i/7 for a given platform. Anyone who has ever studied
the assembly output of a contemporary compiler in recent years knows that,
and wouldn't bother to figure how to do it with shifts and subtractions.

Just don't get too carried away with the assembly stuff and keep in mind
that different compilers use different solutions.

--
Peter van Merkerk
peter.van.merkerk(at)dse.nl

Jul 19 '05 #4
On 28 Jul 2003 02:24:13 -0700, ma******@hotmail.com (Marijn) wrote in
comp.lang.c++:
I'd like to know how compilers usually handle static variables that
are declared inside a function (as opposed to static class-members).
Like in:

int counter(){
static int c=0;
++c;
return c;
}

I would assume the compiler changes it into something like this:

bool counter_c_is_initialized = false;
int counter_c;
int counter(){
if (!counter_c_is_initialized){
c = 0;
counter_c_is_initialized = true;
}
++c;
return c;
}
I would certainly hope not, at least not on "regular" desk top
platforms. Generally the initial values for static POD data is in the
executable image file, and it written into the proper place in memory
by the OS program loader at the same time as it writes the executable
binary image into a different part of memory.
Since they do not seem to be initialized when the function is never
called. Am i correct here? So if this is correct there will be an
extra conditional every time the function is called.
Since there is no possible way in a conforming C++ program to find out
the value of that static object without calling the function, it makes
no difference whether it is initialized or not. But why do you think
it is not?
I've lately taken to implementing singletons with a static function
var, something like this:

class Singleton{
public:
static Singleton& get(){
static Singleton single;
return single;
}
private:
Singleton(){}
};

This only works if the constructor does not take arguments, but it
does take care of the destruction of the object when the program
terminates. Any problems with this form of singleons? I guess i do not
have precise control over the order in which such objects get
destructed, so if the destructor depends on another semi-global object
it could cause problems.

Marijn Haverbeke


When you are talking about non-POD objects with constructors, there is
no requirement nor guarantee that they be initialized at load-time.

--
Jack Klein
Home: http://JK-Technology.Com
FAQs for
comp.lang.c http://www.eskimo.com/~scs/C-faq/top.html
comp.lang.c++ http://www.parashift.com/c++-faq-lite/
alt.comp.lang.learn.c-c++ ftp://snurse-l.org/pub/acllc-c++/faq
Jul 19 '05 #5
Jack Klein <ja*******@spamcop.net> wrote in message news:<d4********************************@4ax.com>. ..
Since they do not seem to be initialized when the function is never
called. Am i correct here? So if this is correct there will be an
extra conditional every time the function is called.


Since there is no possible way in a conforming C++ program to find out
the value of that static object without calling the function, it makes
no difference whether it is initialized or not. But why do you think
it is not?


Actually, the variable might be a user-defined class, whose
constructor has side effects. I have a logfile class singleton
initialized as a function static as i described in my first post, and
when it initializes it opens a file and writes something to it. When
my program does not log anything, the logfile is not created, so that
would prove the variable is only initialized when the function is
actually called. Other compilers might do this differently though, i'd
have to check.

Marijn
Jul 19 '05 #6

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

1
by: Jean-Francois Brault | last post by:
I wrote a crappy class for radian angle management. The class consists of an array of radian values. I put all these things in a class in which all methods are static, so I can access it anywhere...
6
by: Dumitru Sipos | last post by:
Hello everybody! is there possible to have a function that is both static and virtual? Dumi.
15
by: Samee Zahur | last post by:
Question: How do friend functions and static member functions differ in terms of functionality? I mean, neither necessarily needs an object of the class to be created before they are called and...
5
by: Tony Johansson | last post by:
Hello experts! Why is not possible to have virtual static members Many thnakn //Tony
3
by: mpatnam | last post by:
I have an executable which links to a static library (.a). I want to provide a hook by overriding a function part of this static library. Eg: I have a function "int blkstart(int i)" in this static...
11
by: Kevin Prichard | last post by:
Hi all, I've recently been following the object-oriented techiques discussed here and have been testing them for use in a web application. There is problem that I'd like to discuss with you...
55
by: Zytan | last post by:
I see that static is more restricted in C# than in C++. It appears usable only on classes and methods, and data members, but cannot be created within a method itself. Surely this is possible in...
32
by: lcdgoncalves | last post by:
Hi everyone Is there a real need to use keyword static with functions, if we simply don't declare their prototypes in .h file? Many textbooks avoid to discuss this matter and/or discuss only...
10
by: Pramod | last post by:
Hello to all of you, I want to know that what's the use to create static object. Thanks You Pramod Sahgal
2
by: Nagrik | last post by:
Dear Group, The book of Bjarne Stroustrup in chapter 5.4.4 says the following "The word static is one of the most overused words in C and C++. For static data members it has both of the...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.