Reputation: 156
In this code I change iType variable which is a function parameter. It works fine, but is it correct?
void ImgCoreQCV::IPThreshold( double dThresh, double dMaxval, int iType, bool bTreshOtsu ) {
if(bTreshOtsu)
iType |= THRESH_OTSU;
if(undoVector.back().channels()!=1)
cvtColor(undoVector.back(),CurImg,CV_BGR2GRAY);
threshold(CurImg,CurImg,dThresh,dMaxval,iType);
}
I mean that I did not create a new variable and has changed it:
int iThreshType = iType;
if(bTreshOtsu)
iThreshType = iType | THRESH_OTSU;
threshold(CurImg,CurImg,dThresh,dMaxval,iThreshType);
Upvotes: 1
Views: 3977
Reputation: 3731
There are a couple of things that you should be clear on regarding function parameters:
void IPThreshold( double dThresh, double dMaxval, int iType, bool bTreshOtsu );
The above function will pass copies of each of the parameter values to the function body. When invoked with a local variable then the value of the local variable is unchanged after you modify it in the function.
void IPThreshold( double& dThresh, double& dMaxval, int& iType, bool bTreshOtsu );
Above the function will use non-const references which means that you can modify the value of the referenced parameter within the function. If you call this version with a local variable and you modify the parameter then the local variable will be modified after the call returns.
You also ask if this is okay... well I personally attempt not to use parameters for this if I can avoid it as I think that return values are generally clearer. However there is nothing wrong with it. The only caveat I would say is that you should be consistent with the meaning of how you pass your parameters.
Upvotes: 1
Reputation: 347
You can create a temporary variable inline of the lowest function call like this:
threshold(CurImg,CurImg,dThresh,dMaxval, bTreshOtsu ? iType|THRESH_OTSU : iType);
Upvotes: 2
Reputation: 6418
It is correct in this particular case, and it has no side effect since the argument here is a copy of the actual parameter passed.
But it might make a trouble in general case, if you unintentially change parameter passed by reference.
Also modifying parameters usually make the code worse readable. And might require more time for understanding what is really happening in the function.
So, generally I wouldn't recommend modifying parameters. Leave this optimization to the compiler.
Upvotes: 2
Reputation: 1
As long you don't have by reference parameters, changing the value won't have any effect outside of your function.
It's fine to do so and you don't need a extra variable.
Upvotes: 2