How does scoping in Matlab work?

前端 未结 4 1873
独厮守ぢ
独厮守ぢ 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:47

    Interesting situation. I doubt if there is detailed information available about how the MATLAB interpreter works in regard to this strange case, but there are a couple of things to note in the documentation...

    The function precedence order used by MATLAB places variables first:

    Before assuming that a name matches a function, MATLAB checks for a variable with that name in the current workspace.

    Of course, in your example the variable fprintf doesn't actually exist in the workspace, since that branch of the conditional statement is never entered. However, the documentation on variable naming says this:

    Avoid creating variables with the same name as a function (such as i, j, mode, char, size, and path). In general, variable names take precedence over function names. If you create a variable that uses the name of a function, you sometimes get unexpected results.

    This must be one of those "unexpected results", especially when the variable isn't actually created. The conclusion is that there must be some mechanism in MATLAB that parses a file at runtime to determine what possible variables could exist within a given scope, the net result of which is functions can still get shadowed by variables that appear in the m-file even if they don't ultimately appear in the workspace.


    EDIT: Even more baffling is that functions like exist and which aren't even aware of the fact that the function appears to be shadowed. Adding these lines before the call to fprintf:

    exist('fprintf')
    which('fprintf')
    

    Gives this output before the error occurs:

    ans =
         5
    built-in (C:\Program Files\MATLAB\R2012a\toolbox\matlab\iofun\fprintf)
    

    Indicating that they still see the built-in fprintf.

提交回复
热议问题