while

This is a discussion on while within the C++ Programming forums, part of the General Programming Boards category; Is it possible to execute a function once while the function is executed within a while-loop? example: Code: // includes ...

  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,062
    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
    Mad OnionKnight's Avatar
    Join Date
    Jan 2005
    Location
    Umeň, Sweden
    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

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