nrhayyal wrote:
thanks for ur reply Karl ,
is there any reason for 'Preferring initialization above assignment'.?
just curious to know about it.
In the worst case there is no difference between initialization and assignment.
Example:
int j = 5;
------
int j;
j = 5;
I would expect both codes to produce identical code.
But: There may be a difference if the variable you define is of
some class type:
std::string Name( "Compiler" );
------
std::string Name;
Name = "Compiler";
Those 2 code snippets do different things. The first snippet uses
a special constructor to create the Name object with a specific value.
The second code snippet however, creates the Name object and initialises
it to an empty string. The following assignment then discards that empty
string and assigns it a new value.
So while in the first case, the whole process is a one-step procedure (create
object with a specific value) it becomes a two-step procedure in the second
case (create empty object, alter empty object).
And then there is of course the case, where assignment simply doesn't work, eg.
because the 'variable' you define is a constant. A constant can only be initialized
but not assigned, hence initialization is the only thing that will work:
const int j = 5; // works
-------
const int j;
j = 5; // does not work. j is const, hence the compiler hinders you
// to change its value.
So all in all: There is no advantage in assignment in all those cases, so why use it?
Get used to use initialization and you have less problems in the long run.
--
Karl Heinz Buchegger
kb******@gascad.at