nargin vs exist

前端 未结 6 2045
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-30 06:46

Given a function like:

function foo(myParam)
if nargin<1
  myParam = \'default value\';
end % if
end % function

I\'ve seen people use so

6条回答
  •  长情又很酷
    2020-12-30 07:31

    I always validate arguments using nargchk, and then go with the nargin tests as you had them. As others pointed out, they're cheaper, and I think clearer.

    In functions that I expect to be re-used heavily, I always put lots of checks up front, and then structure the code to call the real implementation later.

    I also tend to structure optional arguments (when not using varargin) like this:

    function x = myfcn( arg1, opt_arg2 )
    if nargin < 2
       arg2 = 'default';
    else
       arg2 = opt_arg2;
    end
    

    as I think this makes it more obvious when editing the file which arguments are expected to be optional.

提交回复
热议问题