Mark McIntyre said:
(snip example of nested loops)
There's no way to say that.
You can't, unless you know what "some code" inside the inner loop is. A
modern optimising compiler can optimise both these to be identical, if it
can determine there are no side-effects of the inner code. Many compilers
might even unroll both loops entirely and execute 1000 evaluations of
'some
code'.
And then of course modern CPUs can often run such loops as parallel
processes in different pipelines. Again this might (or might not) mean
that
version X was faster than version Y.
This is all in concordance with the 'as if' principle which allows the
compiler and/or hardware to rearrange your code how it likes, as long as
the result is the same as if it hadn't.
(of a once-unrolled loop)
Yes. No. Sometimes. Never.
O'kay! that may be, or may not be TRUE, for generated code
or a particular implementation/hardware combinattion.
Also as per C Standard -
5.1.2.3 Program execution
1 The semantic descriptions in this International Standard describe the
behavior of an
abstract machine in which issues of optimization are irrelevant.
[-snip-]
3 In the abstract machine, all expressions are evaluated as specified by the
semantics.
An actual implementation need not evaluate part of an expression if it can
deduce that
its value is not used and that no needed side effects are produced
(including any
caused by calling a function or accessing a volatile object).
But as per language semantics, as also abstract machine states (for loop)
6.6.5.3 The for statement
1 Except for the behavior of a continue statement in the loop body, the
statement
for ( clause1 ; expression2 ; expression3 ) statement
and the sequence of statements
{
clause1 ;
while ( expression2 ) {
statement
expression3 ;
}
}
are equivalent (where clause1 can be an expression or a declaration). 114
2 Both clause1 and expression3 can be omitted. If either or both are an
expression,
they are evaluated as a void expression. An omitted expression2 is replaced
by a
nonzero constant.
"clause 1" will make the difference, becase it will be evaluated every time
loop is entered.
-Neo