How does scoping in Matlab work?

前端 未结 4 1903
独厮守ぢ
独厮守ぢ 2021-01-04 05:10

I just discovered (to my surprise) that calling the following function

function foo()
if false
   fprintf = 1;
else
  % do nothing
end
fprintf(\'test\')
         


        
4条回答
  •  夕颜
    夕颜 (楼主)
    2021-01-04 05:27

    MATLAB parses the function before it's ever run. It looks for variable names, for instance, regardless of the branching that activates (or doesn't activate) those variables. That is, scope is not determined at runtime.

    ADDENDUM: I wouldn't recommend doing this, but I've seen a lot of people doing things with MATLAB that I wouldn't recommend. But... consider what would happen if someone were to define their own function called "false". The pre-runtime parser couldn't know what would happen if that function were called.

提交回复
热议问题