>>> int i = f();
if ( i )
and
int i;
if ( i = f() )
It seems like the latter would save the assignment if i was
initialized on the definition anyway?
No. In both cases, f() will be evaluated first and then the result
will be affected to 'i'.
What I meant was that in the former case, there is not both an
initialization and an assignment. Or, you might say it does both in
one step.
No. What exactly happens is implementation defined, that is,
int i = f();
could result in
int i(f()); //copy-ctor
or
int i; // nothing
i = f(); // assignment
the former being an optional optimization.
In the latter case, you are definitely doing an
assignment,
Not necessarily.
but isn't i going to be initialized to something, as well?
No, with
int i;
'i' is _not_ initialized and using it would result in undefined behavior.
class T { ... };
class U { ... };
T f();
int main()
{
U u = f();
// could mean
// U u( f() );
// U u( some_ud_conversion(f()) );
// U u; u.operator=( f() );
// U u; u.operator=( some_ud_conversion(f()) );
U u;
u = f();
// could mean
// U u( f() );
// U u( some_ud_conversion(f()) );
// U u; u.operator=( f() );
// U u; u.operator=( some_ud_conversion(f()) );
}
As you noticed, both can result to the same thing or not, depending on the
compiler and its optimizations. A good compiler will make the second
statement look like the first one and the same compiler would make the first
one look like
U u(f());
or
U u( some_ud_conversion(f()) );
if it is possible in that case.
some_ud_conversion could be like a ctor taking a T or if T can be converted
to a U...
BTW, isn't something like that called 'premature optimization'? If you
don't know whether it speeds things up or not, maybe you should wait a bit
or use a profiler to check the real bottlenecks in your program. If it is
only by curiosity, well, that is a good thing.
Jonathan