Set values or not in c ++ variables

7

Good evening. Should I set values in variables when creating them in C ++? An example:

int x = 0;
int y;

What's the difference in these two cases? And what happens in memory when I initialize it with 0 and without it.

    
asked by anonymous 10.12.2015 / 23:48

2 answers

6

In the case presented, both variables would be initialized with value 0 (in the first case explicitly and in the second case because it is the default value for variables of the type concerned).

However, it is important to note the following in a succinct way: assigning values to variables when your declaration is a good practice, since the declaration process implies that it will point to a particular 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 may appear any undetermined a priori and not its default 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 returned result was 36 since it was the value that would have been stored in the particular memory location and not the default value of 0 . In your case it will surely be any other.

In short, some advantages will be:

  • allows for greater readability of the code, as well as better maintenance of the code
  • Prevents any possible execution errors because they are not properly initialized, as well as some errors due to being assigned an undetermined value
11.12.2015 / 00:51
2

Global or static variables not initialized by the programmer are initialized by the compiler with the default constructor. In practice, variables of the "native" types (int, char, bool, etc.) are initialized with 0, converted to the type of the variable (eg for type bool, 0 is converted to false).

PS. the "native" types are usually classified as "POD" (Plain Old Datatype).

#include <iostream>
using namespace std;

int x = 0;
int y;

int main()
{
   cout << "x=" << x << endl; // zero
   cout << "y=" << y << endl; // zero
}

Non-static local variables not initialized by the programmer are initialized by the compiler with the default constructor, with the exception of POD variables (see above for POD).)

In practice this means that for non-static POD non-static local variables the initial value is unpredictable ("junk").

#include <iostream>
using namespace std;

int main()
{
   int x = 0;
   int y;
   cout << "x=" << x << endl; // zero
   cout << "y=" << y << endl; // ???
}
    
01.03.2017 / 21:12