Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is '-1[p]' when p points to an array (of int) index? [duplicate]

Tags:

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?

like image 725
Erik Stroeken Avatar asked Aug 14 '19 17:08

Erik Stroeken


People also ask

What is a fixed point in an array?

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.

Can an array index be a double?

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.

Can you put doubles in an int array?

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.

Is an array variable a pointer in C?

An array is a pointer, and you can store that pointer into any pointer variable of the correct type.


1 Answers

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' */

like image 172
LunarLambda Avatar answered Sep 20 '22 05:09

LunarLambda