Will removing 'const' from a variable in my C++ cause me issues later on? -
i debugging c++ code, , want change value of variable inside particular function. variable passed parameter function using const
keyword, example:
void setrequest(const &data){ ... }
i want change value of variable data
inside function. understand, won't able because data
has been passed function const
.
what wondering, effects removing keyword const
parameter have other allowing me change value of data
inside function? there possibility break other part of code? pitfalls should out when removing const
keyword?
obviously doing affect other functions use data
variable, given information holds same type, wouldn't have thought cause major issues- correct?
an example of want be:
void setrequest(&data){ ... bool match = false; ... if(somecondition){ match = true; } if(match == true){ data = 1; } }
will removing 'const' variable in c++cause me issues later on?
it depends on you're planning variable.
i want change value of variable data inside function. understand, won't able because data has been passed function const.
if remove const
, "data" receive within function copy of original variable. so, if change it, original variable remain untouched.
to modify original variable, need use reference (if data provided), or pointer (if data optional)
is effects removing keyword const parameter have other allowing me change value of data inside function?
removing const parameter increase chance of making bug might waste hours of time. example" (data = x)
instead of (data == x)
. const in place you'll catch problem immediately, regardless of compiler. that's side effect.
is there possibility break other part of code?
it depends on contents of function. example, if take pointer (reference to) non-const data within function, store pointer in global variable , later access data via pointer later elsewhere, break lot of code.
what pitfalls should out when removing const keyword?
const safeguard made programmer. const
reduces chance of making mistake. removing const, increase chance of making mistake. if non-const
parameter passed by value, mistake pretty amount accidental modification of parameter, , effects contained within function. if non-const
parameter reference, affects whether accidental modification visible outside of it.
there numerous ways shoot in both feet @ once passing (warning: bad programming practice) pointers parameter through external/global variables. pretty guaranteed make big mess.
generally want keep reference parameters const unless have change them.
with simple data types (such int) keeping value parameters const not strictly necessary, worth if there's high possibility of random modification.
you want keep class methods not change class’s internal state const
well.
small things keep in control of situation when codebase grows big.
Comments
Post a Comment