Today I stumbled over a C riddle that got a new surprise for me.
I didn't think that -1[p] in the example below would compile, but it did. In fact, x ends up to be -3.
int x; int array[] = {1, 2, 3}; int *p = &array[1]; x = -1[p]
I searched the internet for something like -1[pointer] but couldn't find anything. Okay, it is difficult to enter the correct search query, I admit. Who knows why -1[p] compiles and X becomes -3?
In array one element will be denoted as fixed point if the value is same as its index. This program will return the value if any, otherwise return -1. The array can hold negative numbers also. And the data elements are sorted. Here we will use binary search approach to solve this problem in O(log n) time.
In case it isn't clear, your array cannot be of double length. It's undefined behavior. This is because a double is not an integer, but a rational number that could be an integer.
The length property holds the value of the size of the array. The array can only hold variables of the same type. So you can have an array of ints, or an array of doubles, or an array of Strings, or an array of objects. But, you cannot have an array of doubles and ints, or any mixture of types.
An array is a pointer, and you can store that pointer into any pointer variable of the correct type.
I'm the person that made this "riddle" (see my Twitter post)
So! What's up with -1[p]?
ISO C actually defines [] to be symmetrical, meaning x[y]
is the same as y[x]
, where x and y are both expressions.
Naively, we could jump to the conclusion that -1[p]
is therefore p[-1]
and so x = 1
, However, -1 is actually the unary minus operator applied to the constant 1, and unary minus has a lower precedence than []
So, -1[p]
is -(p[1])
, which yields -3.
This can lead to funky looking snippets like this one, too:
sizeof(char)["abc"] /* yields 'b' */
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