MISRA rule 17.8 prohibits modification of function parameters in the function body. The rationale is that programmers new to C may misinterpret the semantics of doing so.
But in MISRA C++ it seem to be no corresponding rule. Apart from the objections to the practice of modifying parameters is equally valid in C++ there's even more possibility of getting things wrong: with the possibility to pass by reference there's a possibility to actually modify object/variables in the callers scope from the callee. After all it's just an ampersand that makes the (possibly catastrophic) difference.
To give an example: in C++ (as opposed to C) it's now possible to alter the value for the caller by just modify the parameter if it's passed as a reference:
void g(int32_t& x){
if (x == 42) {
x = 43; // must change x so we don't crash and burn
}
do_something(x);
}
void g_caller(void) {
int32_t x = get_value()
g(x);
if (x == 42) {
crash_and_burn();
}
}
But if the variable is not passed by reference it's the same story as for C, the modification of the parameter is not seen by the caller. The same code with just a ampersand removed, with catastrophic consequence just because somebody didn't think modifying parameters passed by value is as shady as in C. Is the programmers intent to make it crash and burn after all? Or did he just miss the fact that the parameter now is sent by value? Maybe x
used to be passed by reference, but now has changed and the poor programmer just intended to fix a bug by modifying x
here? In C++ it's not just newbies that can mistake x = 43
to just be alteration of a local copy.
void g(int32_t x){
if (x == 42) {
x = 43; // must change x so we don't crash and burn
}
do_something(x);
}
void g_caller(void) {
int32_t x = get_value()
g(x);
if (x == 42) {
crash_and_burn();
}
}
This rule wasn't present in MISRA C:2004 either, which is the C version most similar to MISRA C++:2008. MISRA C was updated and much improved in 2012 but MISRA C++ never went through such an update - it is actually getting reviewed and updated right now, but the next version is still a work in progress, yet to be published. Maybe it will get this rule added.
The rule does make sense particularly for situations like the ones you mention in the question - we do get large amounts of troubleshooting questions with this particular bug here on SO.
Notably, this is one of them rules added mainly for the benefit of static analysers. This is exactly the kind of bug that a static analyser is much better at spotting than humans.