Why are multiple, consecutive plusses allowable syntax in MATLAB?

杀马特。学长 韩版系。学妹 提交于 2019-12-23 13:04:55

问题


Does anyone know why this works in MATLAB?

>> 1 ++ 2
ans =
     3

Coming from coding in C, python, Java etc, I find it most counterintuitive that this should work at all. Presumably there's something important about the parser that I don't understand?


回答1:


There's a difference between plus and uplus. I suspect MATLAB takes the first + as plus, and all the others as uplus. Since uplus is by default just "return what's behind", you add 1 and 2, and use a lot of "return what's behind" in between.

a=2;
c=+a % unitary plus
c =
     2
1+2 % addition
ans =
     3
1+++2 % addition and two uplusses
ans =
     3

The reason uplus exists is to allow operator overloading in classes. The same works in other languages, e.g. in C#, to allow for operator overloading in confined classes.


The other reason mentioned in that C# thread is that is changes unsigned shorts to integers, which is not the case for MATLAB:

d=uint8(1)
d =
  uint8
   1
+d
ans =
  uint8
   1
a=+d
a =
  uint8
   1

It does, however, convert a boolean to a double, thanks to Cris Lunego for pointing that out:

+true
ans =
     1
+false
ans =
     0

The following however remains a mystery to me, inspired by Sanjay Manohar's comment:

>> [1 ++ 2]
ans =
     1     2 % Two unary plusses
>> [1 + + 2]
ans =
     3 % A normal plus and a unary one
>> [1++2]
ans =
     3 % A normal plus and a unary one

The same works with multiple plusses, [1 +++..+++ 2], so with all plusses consecutively in the middle generates [1 2], all other combinations (as far as I tested) result in 3. I asked a separate question about this: Why do the plus and unary plus behave strange in array syntax?



来源:https://stackoverflow.com/questions/52555709/why-are-multiple-consecutive-plusses-allowable-syntax-in-matlab

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!