For loops

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • MrPickle
    New Member
    • Jul 2008
    • 100

    For loops

    When I define a for loop like so:

    Code:
    for(initialize; condition; increment)
    {
       //code
    }
    Is the condition only called once?

    For example:
    Code:
    for(unsigned int i = 0; i < foo(); i++)
    {
       //code
    }
    Would foo() be called several times, or only once?

    Sidenote: I know I could easily test this but it's bugging me and I do not currently have a compiler.
  • Tassos Souris
    New Member
    • Aug 2008
    • 152

    #2
    Well if you know the theory behind for loops you know that the condition statement determines whether the body of the loop is to be executed again or not... If the expression evaluates to true then the body of the for loop is executed; otherwise the for loop terminates.

    Comment

    • samimmu
      New Member
      • Mar 2007
      • 32

      #3
      it will be called only once but if u want to call tat function more than one then you need to specify

      for (int i=0; i<8; i++)
      {
      foo();
      }

      it will be called 8 times

      Comment

      • donbock
        Recognized Expert Top Contributor
        • Mar 2008
        • 2427

        #4
        Originally posted by samimmu
        it will be called only once but if u want to call tat function more than one then you need to specify
        Totally untrue.

        If you go through a for-loop N times, then the second clause of the for-instruction will execute N+1. If that clause includes a function call then the function is called that many times. The only exception is if the second clause is a logical expression and short-circuiting prevents the evaluation of all terms in that expression.

        Comment

        • samimmu
          New Member
          • Mar 2007
          • 32

          #5
          actually i tried but it is not working very well, anyways, i have a question?

          Comment

          • samimmu
            New Member
            • Mar 2007
            • 32

            #6
            Originally posted by donbock
            Totally untrue.

            If you go through a for-loop N times, then the second clause of the for-instruction will execute N+1. If that clause includes a function call then the function is called that many times. The only exception is if the second clause is a logical expression and short-circuiting prevents the evaluation of all terms in that expression.
            i have a question can i ask you ?

            Comment

            • maiyappan
              New Member
              • Oct 2009
              • 4

              #7
              untill the value return from the foo() will be greater than i
              the function will be called when condition check occur.

              Comment

              Working...