Fabio Carballo
Fabio Carballo

Reputation: 364

Why this weird code works?

I got the this:

int main(){
    int Array[] = { 10, 20, 30 };
    cout << -2[Array] << endl;
    system("Pause");
    return 0;

}

The output is:

-30

I want to know why the output is -30 and why causes this undefined behavior?

does anyone knows?

Upvotes: 0

Views: 135

Answers (4)

NameRakes
NameRakes

Reputation: 463

It applies the unary operator (-, minus sign) to pointer incremented by the value outside of [] thus: - *(2 + Array). You can check it out by removing the minus sign, thus applying + unary operator. I would NOT recommend using this syntax.

Upvotes: 0

Luke Joshua Park
Luke Joshua Park

Reputation: 9795

In C++, the following statement is true:

a[5] == 5[a]

This is because the syntax using [] is converted to:

*(a + 5)

E.g.

a[5] == *(a + 5)

Which means that

5[a] == *(5 + a)

Thus the notation -2[Array] is converted to - *(2 + Array).

Upvotes: 0

Lightness Races in Orbit
Lightness Races in Orbit

Reputation: 385088

This is fairly simple.

First, let's analyse the expression:

-2[Array]

is

-(2[Array])

Now a[b] is *(a+b) and since addition is commutative this is also *(b+a) i.e. Array[2].

Array[2] is 30; -Array[2] is -30. Thus, -2[Array] is also -30.

I sincerely hope you do not intend to use this in production code.

Upvotes: 1

Matteo Italia
Matteo Italia

Reputation: 126777

-2[Array] is parsed as -(2[Array]), since subscripting has higher precedence than unary minus.

Now, 2[Array] is just a weird way to write Array[2], so you get -Array[2], i.e. -30. No undefined behavior is involved in the whole expression.

Upvotes: 3

Related Questions