June 23rd, 2013, 05:41 PM
Question on the arguments of for
I learned that the arguments for the for loop are
but I saw codes which had 1st and 3rd arguments not of the form "x = " (assigning a value to a variable), but of the form "scanf("%lf", x)".
for(variable initialization; loop condition; variable update)
I confirmed that this works just as well, but I'm confused about exactly what I'm allowed to put in the 1st and third arguments.
instead thinking as
for them, is it more correct to consider them
the statement to be executed once at the beginning of the whole loop
the statement to be executed at the end of each loop?
June 23rd, 2013, 10:56 PM
The first section is usually referred to as the declaration section, the second is usually referred to as the control section, and the last is the iteration section.
From the C11 Draft standard: N1570 Committee Draft — April 12, 2011 ISO/IEC9899:201x
June 24th, 2013, 02:07 AM
June 24th, 2013, 03:33 PM
Not quite, because a statement and an expression are not the same thing. An expression has both value and type, an statement may not have either.
Each of the three elements may be any valid expression, including function calls. I would suggest that any expression involving scanf() is probably ill advised. It is generally best to keep it simple for maintainability and clarity. Any expression involving a function with side-effects as a control for a for-loop is probably a bad idea.
Not all code you don't understand is good code - often the reverse.
is exactly equivalent to
for( e1; e2; e3 )
Generally id e1 and e3 are not related to e2 (in the sense that the are expressions with variables in common), then the second form should be used. Its a style thing however; you can break that guideline, but if you are producing code that others must work on or maintain, no one will thank you for "clever" code.
while( e2 )
June 24th, 2013, 07:23 PM
Not so when body contains break or continue statements.
Originally Posted by clifford