What is the difference between variable initialization and variable assignment?

What is variable initialization?

Variable initialization is giving a value to a variable at the time of defining the variable. There are quite a few methods to give a value to a variable when defining it:

int a(1);
int a{1};
int a=1;

The above 3 variable initialisation methods are the same: set a to 1 when defining it. Pay attention to the third initialization method. Do not confuse it with variable assignment. The “=” in it is not the assignment operator but just a syntax to initialize the variable. It is definitely different from the code below:

int a;
a=1;

where no variable initialization is involved. The variable is uninitialized at definition, then assigned a value using the assignment operator =.

What is the difference between initialization and assignment?

For simple data type, there seems no difference between initializing a variable and defining a variable uninitialized then assigning a value to it. They even produce the same machine code. But variable initialization and assignment are totally different concepts and implemented differently. The difference would be obvious when considering class data type.

class A
{
public:
    A()
    {
    }
    A(int a)
    {
        qDebug()<<"in A(int a)";
        this->a=a;
    }
    A &operator=(int a)
    {
        qDebug()<<"in operator=";
        this->a=a;
        return (*this);
    }

    A &operator=(const A& other)
    {
        qDebug()<<"in operator=(const A& other)";
        this->a=other.a;
        return (*this);
    }

    A(const A& other)
    {
        qDebug()<<"in A(const A& other)";
        this->a=other.a;
    }
    int a;
};

int main(int argc, char *argv[])
{
    A a(1);
    A b{1};
    A c=1;
}

The output is:

in A(int a)
in A(int a)
in A(int a)

So the three initialization methods are all implemented using the same constructor function. Although we define the assignment operator function for the class A, “A c=1″ does not use it, which proves the “=” in variable initialization statement is not the assignment operator.

Let’s check more code:

A d;
d=1;
A e=d;
A f;
f=e;

The output is:

in operator=
in A(const A& other)
in operator=(const A& other)

This verifies that the second and the fifth statements are variable assignment while the third statement is variable initialization although there is a “=” in it. This time, the variable initialization is realized via copy constructor function.

If you like my content, please consider buying me a coffee. Buy me a coffeeBuy me a coffee Thank you for your support!

Leave a Reply