difference question

What is the difference between initialization and assignment?

Initialization gives a variable an initial value at the point when it is created. Assignment gives a variable a value at some point after the variable is created.

I don't get what it is trying to say. Only different is the timing of giving a value? What is the use of it? Could I see the example?
Last edited on
Your first example still falls under the rules of uniform initialization. int x { 15 }; is uniform initialization, with a non-default value.

https://mbevin.wordpress.com/2012/11/16/uniform-initialization/

Your second example tells the compiler to use a default value, a value that depends on the type. With int that would be zero, double is 0.0, etc.

If you are initializing a POD (plain old data such as int) variable with uniform initialization and don't care about what that value is typing the value or letting the compiler select the default value is personal choice. I prefer to let the compiler decide.

You should do what makes it easier for you to read and understand the code.

One major advantage to uniform initialization is the compiler catches simple programming "boo-boos," such as initializing an int with a double value from a previously created variable or a function. The compiler warns about a type narrowing. If I really do want to assign a double to an int I do a cast so I know the conversion is deliberate.

https://www.learncpp.com/cpp-tutorial/explicit-type-conversion-casting-and-static-cast/

Using the assignment operator= when initializing a variable is the old school way to do things. int x = 15;

Trying to reassign a new value to an already created variable with uniform initialization won't work:
201
202
203
204
205
int x { };

// lots of code to do stuff

int x { 25 };


I know, I've accidentally tried more than once. ;)
After reread few time, I think I get what my question mean
1
2
3
4
int x;

x = 5
// this is assignment 


1
2
3
4
5
6
int x = 5

or

int x{5}
// this is initialization 
Last edited on
Correct.
for simple things like integers, it does not make a lot of difference (there may be an assembly level tweak on initialize that saves a nano second or two, but meh).
for a class, though, the constructor is called when you initialize, and the assignment operator is called when you assign, and while normal people would set it up so there isnt much difference in the final result after those, they COULD be set up to do something "really weird", for example assignment could clear a dozen fields to zero and init could set them all to random values. Or whatever else. So which one is being called can matter a bit more for oddball objects.
that is to say
thing x = values;
is not assured to be the same as
thing x;
x = values;
even though normally, it will be and should be.
Topic archived. No new replies allowed.