Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Any difference between '+' and '&' for String concatenation?

Tags:

string

vba

I have very recently realized that VBA supports also the operator + to concatenate String type, and not only &. Hence, if

Dim a As String, b As String
a = "Stack "
b = "Overflow"

the following statements will produce the same result:

>> a + b '--> "Stack Overflow"
>> a & b '--> "Stack Overflow"

In my limited experience I have never found in any language two operators doing always the same thing. I feel like VBA is tending to merge to other common languages (using only + for concatenating strings) but still supporting the & for old-school VB developers.

But this doesn't sound much as a technical explanation, so I'd like to ask the following question: is there any practical difference between the two operators? Does a case where using + rather than & yields a different result?

What I have in mind

A possible "like-answer" that I have in mind but cannot find anywhere in the web was inspired by JavaScript, where you can use the == and === almost everywhere with the same behavior, except that The identity (===) operator behaves identically to the equality (==) operator except no type conversion is done, and the types must be the same to be considered equal.

like image 635
Matteo NNZ Avatar asked Apr 24 '15 16:04

Matteo NNZ


1 Answers

OK, I found it. Try this:

Debug.Print "3" + 4 '--> 7

and compare it to this:

Debug.Print "3" & 4 '--> "34"

Ahh! See the difference now? The choice of & vs. + affects what the default type it coerces the operands of these expressions to.

The + will try to convert the String in Numeric and, if possible, will treat them as such. The &, on the other hand, will keep treating the elements as String even if they're both convertible in Numeric.

like image 113
RBarryYoung Avatar answered Sep 27 '22 22:09

RBarryYoung