running code EXACTLY once

This is a discussion on running code EXACTLY once within the C++ Programming forums, part of the General Programming Boards category; How can I guarantee it runs code only once? using static and an if statement doesn't count....

  1. #1
    Registered User
    Join Date
    Sep 2002
    Posts
    417

    running code EXACTLY once

    How can I guarantee it runs code only once?

    using static and an if statement doesn't count.

  2. #2
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    Can you be more specific? The entire program? One function?
    My best code is written with the delete key.

  3. #3
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    one line...

    such as this:
    Code:
    void func1()
    {
             //code
            FlushConsoleInputBuffer(
    		hStdin   // handle to console input buffer
    	); // ONLY RUN THIS ONE TIME, even if called multiple times
             // more code
    }

  4. #4
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    One easy way is to use a static variable. The first time through you initialize it to a value, then reset it to something different. Every subsequent call of the function ignores the new value with an if statement:
    Code:
    #include <stdio.h>
    
    static void f(void)
    {
        static firstTime = 1;
    
        if (firstTime)
        {
            printf("Only once\n");
            firstTime = 0;
        }
    
        printf("Every time\n");
    }
    
    int main(void)
    {
        f();
        f();
        f();
        f();
        f();
        f();
    
        return 0;
    }
    My best code is written with the delete key.

  5. #5
    Registered User
    Join Date
    Sep 2002
    Posts
    417

    Re: running code EXACTLY once

    Originally posted by Trauts
    using static and an if statement doesn't count.
    Ignoring that...

    What is the difference between a static function and a non static?

    I know what a static variable does... but not what the function would do.

  6. #6
    jasondoucette.com JasonD's Avatar
    Join Date
    Mar 2003
    Posts
    278
    I think he means using a static variable within the function... but I'm not sure.

    You could call a function pointer, which is initialized to the function to be called only once. This function could change the function pointer to point to a function that does nothing before it returns. This ensures that the function is only ever called once. Ugly, but effective, and within your given restrictions.

  7. #7
    Registered User major_small's Avatar
    Join Date
    May 2003
    Posts
    2,787

    i have a question:

    why use a static variable instead of an int or bool?
    Join is in our Unofficial Cprog IRC channel
    Server: irc.phoenixradio.org
    Channel: #Tech


    Team Cprog Folding@Home: Team #43476
    Download it Here
    Detailed Stats Here
    More Detailed Stats
    52 Members so far, are YOU a member?
    Current team score: 1223226 (ranked 374 of 45152)

    The CBoard team is doing better than 99.16% of the other teams
    Top 5 Members: Xterria(518175), pianorain(118517), Bennet(64957), JaWiB(55610), alphaoide(44374)

    Last Updated on: Wed, 30 Aug, 2006 @ 2:30 PM EDT

  8. #8
    Code Goddess Prelude's Avatar
    Join Date
    Sep 2001
    Posts
    9,796
    >Ignoring that...
    Whoops, missed that. Why can't you use it? Otherwise you would end up with deterministic variables and screwy logic.

    >What is the difference between a static function and a non static?
    A static function has file linkage, non-static functions are external. It's the C way of having a function visible only to the file that it's declared in.

    >why use a static variable instead of an int or bool?
    Because a static variable is initialized once on the first call of the function, after that it is never initialized again as it persists until the program terminates. It's a trick that saves you from using more awkward methods.
    My best code is written with the delete key.

  9. #9
    Registered User
    Join Date
    Sep 2002
    Posts
    417
    Originally posted by Prelude
    It's a trick that saves you from using more awkward methods.
    i.e. global variables

  10. #10
    Cat
    Cat is offline
    Registered User
    Join Date
    May 2003
    Posts
    1,571
    Sorry if I'm bumping an age-old thread, I actually meant to reply to this a while ago, but wasn't at my computer when I thought of this solution, and I forgot until now. Using an "if" is NOT required in this method; using a static variable is. As you said you can't use the static AND an if, this follows the letter of the law.

    The secret is to do your code WITHIN the initialization of a static variable within a function, because that is guaranteed to happen exactly once, the first time the function happens.

    Code:
    void function(){
        static int i = (
            std::cout << "This is really long" <<std::endl,
            std::cout << "Note it uses commas" <<std::endl,
            std::cout << "And not semicolons!" <<std::endl,
            std::cout << "It's only done once" <<std::endl,
            0); // we end with something we can instantiate i with
        std::cout << "We always do this!" << std::endl;
    }
    Here, we use the parentheses to force an order of operations (otherwise, it would try to initialize i with an &ostream, which won't work.) We want to do all the comma operations first, then the initialization.

    You notice there are no semicolons; this is ONE expression. It uses the comma operator four times.

    So long as the very last thing in our chain of comma operators is something that can legally instantiate an integer, it's OK. You could put as many lines as you like in there, and there is no limit on what can go in the middle of the chain, just make sure the very last thing is an integer.

    The nice thing about this is that it happens in the scope of the function, so you can use all the variables of the function. You could also do:

    static int i = function2(/*parameters*/);

    where function 2 accepts/modifies the necessary variables via parameter list, and returns an int.

    Output of calling the above code five times would be:

    This is really long
    Note it uses commas
    And not semicolons!
    It's only done once
    We always do this!
    We always do this!
    We always do this!
    We always do this!
    We always do this!

  11. #11
    Registered User
    Join Date
    Dec 2001
    Posts
    104
    originally posted by Cat
    Code:
    void function(){
        static int i = (
            std::cout << "This is really long" <<std::endl,
            std::cout << "Note it uses commas" <<std::endl,
            std::cout << "And not semicolons!" <<std::endl,
            std::cout << "It's only done once" <<std::endl,
            0); // we end with something we can instantiate i with
        std::cout << "We always do this!" << std::endl;
    }
    This is probably beside the point, but why do you need the
    std:: in front of cout here. It appears to me that this is not always needed.

  12. #12
    C++ Developer XSquared's Avatar
    Join Date
    Jun 2002
    Location
    Ontario, Canada
    Posts
    2,718
    You can either use 'using namespace std' or prefix all members of the std namespace with 'std::'.
    Naturally I didn't feel inspired enough to read all the links for you, since I already slaved away for long hours under a blistering sun pressing the search button after typing four whole words! - Quzah

    You. Fetch me my copy of the Wall Street Journal. You two, fight to the death - Stewie

  13. #13
    jasondoucette.com JasonD's Avatar
    Join Date
    Mar 2003
    Posts
    278
    (Edit: this was in reply to kes103's post. X was a little bit faster than me.)

    Because cout and endl are within the std namespace. If you have:
    Code:
    using namespace std;
    at the start of the program, then you do not need to qualify it with "std::", since it will find them in the namespace you are 'using'.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem in running turbo C code
    By bulogi in forum C Programming
    Replies: 6
    Last Post: 04-26-2008, 11:25 PM
  2. running a kasumi code
    By bubblegum in forum C Programming
    Replies: 0
    Last Post: 03-05-2008, 10:52 PM
  3. Running code in the background
    By random in forum C++ Programming
    Replies: 3
    Last Post: 12-10-2005, 02:04 PM
  4. Problem : Threads WILL NOT DIE!!
    By hanhao in forum C++ Programming
    Replies: 2
    Last Post: 04-16-2004, 02:37 PM
  5. Replies: 4
    Last Post: 01-16-2002, 12:04 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21