Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why there is no difference between initialization and assignment for the build-in type in C?

I am reading a book and it says that there is no difference between initialization and assignment for the built-in type in C or C++, but the type like string in C++, there are difference. Why? Why there is no difference for the built-in types in C?

like image 953
user2131316 Avatar asked Sep 18 '13 11:09

user2131316


People also ask

What is the difference between initialization and assignment in C?

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.

What is the difference between initializing declaring and assigning a variable?

Initialization is the process of assigning a value to the Variable. Every programming language has its own method of initializing the variable. If the value is not assigned to the Variable, then the process is only called a Declaration.

Why is it important to initialize assign a value to a variable before using it?

In addition, when variables are initialized upon declaration, more efficient code is obtained than if values are assigned when the variable is used. A variable must always be initialized before use. Normally, the compiler gives a warning if a variable is undefined. It is then sufficient to take care of such cases.

What is the difference between initialization and instantiation?

Initialization: Assigning a value to a variable is called initialization. For example, cost = 100. It sets the initial value of the variable cost to 100. Instantiation: Creating an object by using the new keyword is called instantiation.


1 Answers

Because the standard types like int don't have constructors. These

int x = 123;
int y;
y = 123;

are the same (at the beginning, y will have some random/garbage value).

While creating an object will call its constructor. So, for example:

std::string s = "123";
std::string y;
y = "123";

s will be created and initialized immediately, while y will be created, its values will be initialized (based on std::string's constructor) and later, they will be changed during the operator=.

like image 84
Kiril Kirov Avatar answered Nov 11 '22 04:11

Kiril Kirov