Thread: static functions

  1. #1
    Registered User
    Join Date
    Apr 2011
    Posts
    62

    static functions

    Someone said to me once that when possible I should use static functions because it helps the compiler "in-line operations" (which I admittedly have no idea of the meaning). I was looking for documentation on this and found none and was hoping someone could clarify me on if/how that works. I'm actually not seeing the application of a static function in general and would appreciate some help there as well.

    the class that I'm currently working at is something that only requires one object in the entire program and initially I was creating one in the main and passing by reference in the constructor to other classes that would need it.
    As a way to simplify things I figured I could make all data members of the class static and therefore I can simply create new objects wherever I need and the relevant data is shared between them. the functions however I don't know if I should share or not. the end result seems to be the same unless there are some sort of compiler efficiency issues.

  2. #2
    C++ Witch laserlight's Avatar
    Join Date
    Oct 2003
    Location
    Singapore
    Posts
    28,413
    Quote Originally Posted by killme
    Someone said to me once that when possible I should use static functions because it helps the compiler "in-line operations" (which I admittedly have no idea of the meaning). I was looking for documentation on this and found none and was hoping someone could clarify me on if/how that works.
    I have never heard of this advice. In C++, the inline keyword is what I would use to hint to the compiler that I think a function is a good candidate to be inlined, i.e., instead of having a function call, the content of the function is placed at the point of the call. Note that this is only a hint so the compiler is free to ignore it.

    Quote Originally Posted by killme
    I'm actually not seeing the application of a static function in general and would appreciate some help there as well.
    In C, a static function would be used to make a function local to a translation unit. For example, if a function is implementation detail in a source file, you would declare it static so that say, there would be no conflict with an identically named function in another source file. In C++, this is superseded by the defining of functions within unnamed namespaces, so I do not use static non-member functions.

    Quote Originally Posted by killme
    the class that I'm currently working at is something that only requires one object in the entire program and initially I was creating one in the main and passing by reference in the constructor to other classes that would need it.
    Would it always be an error to have more than one such object and does the object need to be globally accessible? If so, then perhaps you should look into the singleton pattern. Otherwise, creating the object in the global main function and passing it to functions that need it is fine. You could disable the copy constructor and copy assignment operator by declaring them private if it makes sense to do so.
    Quote Originally Posted by Bjarne Stroustrup (2000-10-14)
    I get maybe two dozen requests for help with some sort of programming or design problem every day. Most have more sense than to send me hundreds of lines of code. If they do, I ask them to find the smallest example that exhibits the problem and send me that. Mostly, they then find the error themselves. "Finding the smallest program that demonstrates the error" is a powerful debugging tool.
    Look up a C++ Reference and learn How To Ask Questions The Smart Way

  3. #3
    Registered User
    Join Date
    Apr 2013
    Posts
    1,658
    In terms of optimization, if functions are declared as static, then since the compiler knows all the calls to those static functions are within a single source file (and any includes), global optimization may be improved, such as using registers instead of the stack for certain calling sequences. As far as "in-lining" functions, even if a function is not static, there's no reason a compiler could not "in-line" instances of a function within the source module that includes the function.

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Even better is to use a compiler that uses link-time generation. This allows the compiler to see the "entire" program and as such perform global optimizations such as the above and many more.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

  5. #5
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Quote Originally Posted by killme View Post
    Someone said to me once that when possible I should use static functions because it helps the compiler "in-line operations" (which I admittedly have no idea of the meaning). I was looking for documentation on this and found none and was hoping someone could clarify me on if/how that works. I'm actually not seeing the application of a static function in general and would appreciate some help there as well.
    Inlineing is the act of replacing a call to a function with the body of the function, thereby eliminating the overhead of calling a function. This can be a very fruitful optimization for some functions, such as very short functions. A compiler will first try to inline functions when compiling each translation unit, the cpp fle and all included headers, but can only do so if the function body is in the same translation unit. A compiler will also try to inline function when linking your whole project together, so even if a function is not marked static or inline, it may still be inlined anywhere. However, this second pass of inlining is generally less aggressive.


    In C++ and C99 the preferred way to help the compiler inline functions is to put them in the header and marking them as inline. In C89, the inline keyword is not available, so as an an alternative way of putting functions in headers for inlineing is by marking them static. The two key words are not mutually exclusive, so you could also declare a function as static inline, though why you would is dubious. C++ also provides a facility called unnamed namespaces that is almost identical to static functions in behavior.

    The inline keyword allows a function to be declared in multiple translation units, provided that the same sequence of tokens is used to define the function. So you can put the function in the header. Note that if you don't use the same sequence of tokens, the compiler is not required to issue a diagnostic.

    The static keyword allows multiple copies of a function to exist, one per translation unit. This has a similar effect of allowing you to put the definition in the header, but is less efficient for the compiler. Also, the compiler may warn you about unused static functions if set to do so. Static function may be useful for purposes other than inlining.

    Unnamed namespaces are identical in what I described about static functions, and are prefered over static functions, mostly for elegance reasons; unnamed namespaces can wrap more than just functions. They also be used as template arguments, whereas static functions can't. I suspect, however, that there are rare cases that static functions could be optimized better than unnamed namespaces, due to the details of how they are commonly implemented.

    In the three alternatives, static variables inside the function behave differently. For an inline functions, there is one version of each static variable in the whole program. For static and unnamed namespace functions, there is one version for each translation unit. Of course, static function variables should be avoided anyway because they have global scope and because they are not thead safe.


    Putting a function in the header and marking it inline (or static) is an optimization tweak, which I'd recommend not using unless performance is critical and you're profiling to establish that it helps.
    Last edited by King Mir; 09-15-2013 at 10:46 PM.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

  6. #6
    Registered User
    Join Date
    Sep 2013
    Posts
    1
    Staic functions:

    • When a member function is declared as static, it can access only other static members and not non-static members.

    • Since memory to member function is allocated only once, static member function is also created with other member functions and its definition appears within class unlike static data. It is not the member any object and created for class, which is always called with the class name and ( :: )

    • Find the Example with explanation:
    • cbtSAM FREE computer Training / Tutorials, cpp Static functions

  7. #7
    Registered User
    Join Date
    Jun 2005
    Posts
    6,815
    Quote Originally Posted by samcpp View Post
    When a member function is declared as static, it can access only other static members and not non-static members.
    Not true. Any function, static or otherwise, can access non-static members of a class if they have a pointer or reference to an instance of that class.

    Code:
    #include <iostream>
    class X
    {
        public:
    
            X() : x(42) {};
            static int get();
    
         private:
            int x;
    }
    
    X a;
    
    int X::get()
    {
        return a.x;
    }
    
    int main()
    {
         std::cout << X::get() << '\n';
         return 0;
    }
    Quote Originally Posted by samcpp View Post
    Since memory to member function is allocated only once, static member function is also created with other member functions and its definition appears within class unlike static data. It is not the member any object and created for class, which is always called with the class name and ( :: )
    The first sentence here is incorrect to the point of being meaningless. Some implementations (aka compilers, etc) might do it that way, but there is no requirement that they do so.

    The second sentence is incorrect, since a non-static member function of a class can call a static member of that class without qualification (i.e. without using the scope operator). [There are some possibilities for ambiguity if a "using" directive is in play, but that's another story.].

    Quote Originally Posted by samcpp View Post
    I'll pass. Two out of two examples of your site are demonstrably wrong. That is not a glowing testament to quality of examples on your site.
    Last edited by grumpy; 09-17-2013 at 06:34 AM.
    Right 98% of the time, and don't care about the other 3%.

    If I seem grumpy or unhelpful in reply to you, or tell you you need to demonstrate more effort before you can expect help, it is likely you deserve it. Suck it up, Buttercup, and read this, this, and this before posting again.

  8. #8
    Registered User
    Join Date
    Oct 2006
    Posts
    3,445
    Quote Originally Posted by grumpy View Post
    Two out of two examples of your site are demonstrably wrong.
    not to mention the code formatting is literally nonexistent. you have no indentation, making brace matching extremely difficult, and it just generally makes your code unpleasant to read.
    What can this strange device be?
    When I touch it, it gives forth a sound
    It's got wires that vibrate and give music
    What can this thing be that I found?

  9. #9
    Registered User
    Join Date
    Apr 2006
    Posts
    2,149
    Moreover the OP is asking about the kind of static functions that pertain to inlining, not static class members. So your comments are not only wrong, they're also about something completely different.
    It is too clear and so it is hard to see.
    A dunce once searched for fire with a lighted lantern.
    Had he known what fire was,
    He could have cooked his rice much sooner.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Static Functions
    By JohnLeeroy in forum C++ Programming
    Replies: 1
    Last Post: 04-20-2011, 03:45 AM
  2. static functions
    By ashaikh432 in forum C# Programming
    Replies: 15
    Last Post: 08-27-2010, 03:22 PM
  3. Calling non-static functions on static variables
    By pandu in forum C++ Programming
    Replies: 14
    Last Post: 06-19-2008, 03:07 AM
  4. Static Functions
    By Dae in forum C++ Programming
    Replies: 4
    Last Post: 10-23-2005, 08:45 PM
  5. Static functions
    By Morgan in forum C Programming
    Replies: 2
    Last Post: 01-20-2003, 05:00 AM