Question:
Good night. Should I or should I not set values in variables when creating them in c++? An example:
int x = 0;
int y;
What is the difference in these two cases? And what happens in memory when I initialize it with 0 and without it.
Answer:
In the case presented, both variables would be initialized with the value 0 (in the first case explicitly and, in the second, because it is the missing value for variables of the type in question).
However, it is important to emphasize the following, in a succinct way: assigning values to variables when they are declared is a good practice, since the declaration process implies that it will point to a certain memory location. When accessing the variable, the program will return the value stored in that location (in many cases it is simply garbage). If the variable is not initialized, it is possible that any a priori undetermined value will appear and not its supposed missing value.
Pay attention to this example:
#include <iostream>
using namespace std;
struct teste{
int variavel;
};
int main(){
teste a;
cout << a.variavel;
return 0;
}
In my case, the result returned was 36
as it was the value that happened to be stored in the particular memory location and not the default value of 0
. In your case it will surely be something else.
In short, some advantages will be:
- allows for greater code readability, as well as better code maintenance
- avoids that possible execution errors may arise because they are not properly initialized, as well as some errors due to the fact that an indeterminate value is assigned