Thread: while

  1. #1
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312

    while

    Is it possible to execute a function once while the function is executed within a while-loop?

    example:

    Code:
    // includes and stuff
    
    void greet()
    {
      cout << "Greetings!";
    }
    
    int main()
    {
    
      while (bla == "bla")
      {
        greet();  // execute once?
      }
    }
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    65
    The easiest would be moving the call outside the loop.

    But since you ask the question, there must be a reason why you can't or don't want to do it.

    What is that reason?

  3. #3
    Devil's Advocate SlyMaelstrom's Avatar
    Join Date
    May 2004
    Location
    Out of scope
    Posts
    4,079
    Similarly, if it had to be in the loop, you could simply put a count on the loop and put your function in a conditional statement that only executes on the first count.

    Code:
    int loopCount = 0;
    
    while (blah == "Blah") {
       loopCount++;
    
       if (loopCount == 1)
            greet();
    }
    Sent from my iPadŽ

  4. #4
    Registered User OnionKnight's Avatar
    Join Date
    Jan 2005
    Posts
    555
    Code:
    // includes and stuff
    
    void greet()
    {
      cout << "Greetings!";
    }
    
    int main()
    {
      bool hasbeenused = false;
    
      while (bla == "bla")
      {
        if (!hasbeenused) {
          greet();  // execute once?
          hasbeenused = true;
        }
      }
    }

  5. #5
    C / C++
    Join Date
    Jan 2006
    Location
    The Netherlands
    Posts
    312
    thx for the replys!
    Operating Systems:
    - Ubuntu 9.04
    - XP

    Compiler: gcc

Popular pages Recent additions subscribe to a feed