What’s the benefit of making const variable then, If we can change the value by Initialization List.
What's the benefit of making const variable
hi @cbcao263, let’s have some discussion on the benifits of const variable
There are several advantages of using const in C or C++:
- Code Maintenance: Say I have a need to use the speed of light for calculations throughout my project. The speed of light is not going to change so there is no need for a variable. I could simply copy and paste 300,000,000 (obviously without the commas) anytime I need the speed of light (in meters per second). This will work fine for now but down the road my calculations may require more precision so if I want to change 300,000,000 to 299,792,458 it will be a fairly painful process if I used this value a lot in my code. If I use a const I can use this the name of this const throughout the code so if I need to change its value I can just change it once at the beginning of the code.
- Memory: This isn’t usually relevant given the computing power of modern devices but for software on embedded devices there may not be the RAM space for variables and by using a const its value is put into the program when the code is compiled. This allows storage space (on the HDD/SSD) to be used instead of the RAM.
- Accidental Changes: If you need a value to stay constant use a const so that you don’t accidentally change its value later on because you forget that you need its value to remain the same. Think of it this way, if its value is not going to change throughout the code why wouldn’t you use a const.
we are not changing the value using initialization list , changing means that variable had some value and is changed by some other value. but in initialization list , we are initializing the value of the variable, that means the const value will from now on will stick with the value provided during initialization and cannot be changed
In case of any doubt feel free to ask
mark your doubt as resolved if you got the answer
I hope I’ve cleared your doubt. I ask you to please rate your experience here
Your feedback is very important. It helps us improve our platform and hence provide you
the learning experience you deserve.
On the off chance, you still have some questions or not find the answers satisfactory, you may reopen
the doubt.