I ran into this beauty, but I can't really understand it!
#include <iostream>
using namespace std;
int main() {
int array[] = {10, 20, 30};
cout << -2[array];
return 0;
}
It prints -30
.
Thank you in advance
Edit: Not a duplicate of this question because of the "-" sign.
This is funny and simple. -array[2]
is the same as -*(array + 2)
, which is the same as -*(2 + array)
which is the same as -2[array]
, which is -30.
There is already a duplicate for general case of using square brackets with arrays (With arrays, why is it the case that a[5] == 5[a]?), but the quirk here is the unary -
operator in front.
It might seem intuitive to assume that the actual array index would be -2
, like array[-2]
.
But this is not happening due to operator precedence rules:
operator []
has higher precedence than unary -
, and as such is applied first. I've shown the tranformation with 'conventional' array subscription to make this more intuitive
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With