Connecting Tech Pros Worldwide Help | Site Map

For loops

MrPickle's Avatar
Member
 
Join Date: Jul 2008
Posts: 98
#1: Sep 16 '09
When I define a for loop like so:

Expand|Select|Wrap|Line Numbers
  1. for(initialize; condition; increment)
  2. {
  3.    //code
  4. }
Is the condition only called once?

For example:
Expand|Select|Wrap|Line Numbers
  1. for(unsigned int i = 0; i < foo(); i++)
  2. {
  3.    //code
  4. }
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.
Member
 
Join Date: Aug 2008
Posts: 121
#2: Sep 16 '09

re: For loops


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.
Member
 
Join Date: Mar 2007
Posts: 32
#3: Sep 21 '09

re: For loops


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

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

it will be called 8 times
Expert
 
Join Date: Mar 2008
Location: Naperville, Illinois U.S.
Posts: 828
#4: Sep 21 '09

re: For loops


Quote:

Originally Posted by samimmu View Post

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.
Member
 
Join Date: Mar 2007
Posts: 32
#5: Sep 21 '09

re: For loops


actually i tried but it is not working very well, anyways, i have a question?
Member
 
Join Date: Mar 2007
Posts: 32
#6: Sep 21 '09

re: For loops


Quote:

Originally Posted by donbock View Post

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 ?
Newbie
 
Join Date: Oct 2009
Location: chennai
Posts: 4
#7: Oct 6 '09

re: For loops


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