Tuesday, July 14, 2009

In C++, What use do we have for constants instread of variables?

an example would be


const double PI=3.14;


for(float x=PI;whatever;x++){


cout%26lt;%26lt;x%26lt;%26lt;endl;


}





that was just an example of using constants;





but you could do the same without using constants;


double PI=3.14;


for(int x=PI;whatever;x++){


//This would also work


}








so what use do we have of using constants for somethings instread of variables

In C++, What use do we have for constants instread of variables?
Constants don't change, variables can change.





You can't mistakingly change a constant. For example like this:





if(pi=3.00){


//do something


}





If pi is a constant, you'll get an error message. If pi is a variable, you won't.
Reply:It's just so that no one else changes them. It also indicates to other programmers that the variable is never intended to change.
Reply:Variables use more memory. So if you have a large program you need to consider this.
Reply:Its just validation, it eliminates problems caused by changing variables.





It prevents you from accidentally changing its value and messing everything up. Its very professional. I must admit, I dont use them but I should do.


No comments:

Post a Comment