Dec 15, 2011

When you initialize variables to zero and when


When I started learning to program in c + + (I think one never ends) taught me to always be initialized to zero or some other value variables, because if not, can take values ​​that could ruin rare our program.
Let's see if the legend is true:
 1
 2
 3
 4
 5
 6
 7
 8
 # Include <iostream>
 using namespace std;

 int main ()
 {
     int var1;
     court <<var1;
 } 
Well, with my compiler it is, an uninitialized variable takes values ​​rare. But if you have set in my programs, I always initialize my variables, why? Because it is not always necessary.
The rule is quite simple: "If the first statement in which we use our variable assignment is not necessary to initialize it." For example:
 cin>> var1 / / do not need to initialize
 var2 = 14, / / no need to initialize
 court <<var3 / / is necessary to initialize
 var4 = cos (45), / / no need to initialize
 var5 + + / / need to initialize
 if (var6! = 7) / / You must initialize
 cin. getline (var7) / / do not need to initialize 
We can continue initializing all the variables we use, but if necessary we initialize only going to give the impression that we know what we're doing XD

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More

 
Design by Free WordPress Themes | Bloggerized by Lasantha - Premium Blogger Themes | Premium Wordpress Themes