Re: The for-init-statement in a for statement
"Matthias Hofmann" <hofmann@anvil-soft.com> skrev i meddelandet
news:44c2219a$0$24892$9b4e6d93@newsread4.arcor-online.net...
Hello everybody!
When I first learned learned C++, I often encountered statements
like
for ( ;; ) {}
instead of
while ( true ) {}
Also, I found code in the VC++ implementation of STL algorithms that
omitted
the for-init-statement in for statements, for example in:
template <class _FwdIt, class _Ty> inline
void fill( _FwdIt _First, _FwdIt _Last, const _Ty& _Val )
{
for( ; _First != _Last; ++_First )
_First = _Val;
}
This seems to make perfect sense, but 6.5.3/1 of the C++ Standard
says that
the for-init-statement cannot be omitted. Does that mean that the
implementation of fill() above is not portable? Would it have to be
rewritten as follows to be standard compliant?
No, the for-init-statment has one alternative where the expression is
optional, and only the semicolon is required. That is why there is a
semicolon directly inside the opening parenthesis.
template <class _FwdIt, class _Ty> inline
void fill( _FwdIt _First, _FwdIt _Last, const _Ty& _Val )
{
while ( _First != _Last )
{
_First = _Val;
++_First;
}
}
By the way, I noticed that my version of the C++ Standard defines
the for
statement as follows:
for ( for-init-statement condition opt ; expression opt ) statement
I guess there is a semicolon missing right before "condition"?
No, the for-init-statement is defined as
expression(opt) ;
so it contains the semicolon (but perhaps not an expression).
Bo Persson
[ See http://www.gotw.ca/resources/clcm.htm for info about ]
[ comp.lang.c++.moderated. First time posters: Do this! ]