Search code examples
matlaboctaveoperator-precedence

Are matlab function parameters evaluated in order, from left to right?


And is the following code well defined?

print_factor(p(++k), p(--k));

And how do things look like in octave?


Solution

  • Do not do this! The code is valid in both MATLAB and Octave, but behaves very differently.


    MATLAB:

    The code you have is actually valid MATLAB code. However, it doesn't do what you expect.

    In many languages, ++k means increment k and return it. In MATLAB, ++k is just the same as k, because in MATLAB: 3 == +3 == ++3 == +++++++3. The same goes for --k. This is --k == -(-k) == +k == k. Similarly, in many languages k++ means return k, then increment it. In MATLAB however, are k++ and k-- not valid syntax and causes syntax error.

    Your code is (in MATLAB) equivalent to:

    print_factor(p(k), p(k));
    

    Testing the code in MATLAB with two example functions for p and print_factor:

    p = @(x) 2*x;
    print_factor = @(x,y)disp([x,y]);
    k = 2;
    print_factor(p(++k), p(--k));
     4     4
    k    
    k =    
         2
    

    Octave:

    In Octave, the operators are defined, and are evaluated left to right, but I don't think the official documentation regarding the increment operators says anything about this. It might be platform dependent, as it is in C++. However, it's likely interpreted in the same way other expressions are evaluated, see the example in the bottom.

    You can test it online here.

    The exact same code in Octave:

    p = @(x) 2*x;
    print_factor = @(x,y)disp([x,y]);
    k = 2;
    
    print_factor(p(++k), p(--k));
       6   4
    k
    k =  2
    
    print_factor(p(++k), p(++k));
       6   8
    k
    k =  4    
    

    As Dan commented: Writing code in Octave that doesn't follow the MATLAB syntax is not a good idea. You will have to rewrite it in case you ever want to run it in MATLAB.