6.9k views
0 votes
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?

User Jnpdx
by
7.7k points

1 Answer

4 votes

Final answer:

In C, the expression -1[p] compiles and evaluates to the value -3 because array indexing in C is done using pointer arithmetic.

Step-by-step explanation:

In C, the expression -1[p] compiles and evaluates to the value -3 because array indexing in C is done using pointer arithmetic. In C, the expression *(p + n) is equivalent to array[n], where p is a pointer and n is the index you want to access. This is the reason why -1[p] compiles and works as expected.

When the expression -1[p] is evaluated, it can be rewritten as -*(p + 1). Here, p + 1 is equivalent to &array[1] + 1, which points to the next element in the array (which is array[2]). So, -*(p + 1) is equivalent to -array[2], which evaluates to -3.

It's worth noting that this syntax is not commonly used and can be confusing. It's generally recommended to use the more readable syntax array[n] instead of *(p + n) or n[p].

User Daoway
by
7.7k points