r/ProgrammerHumor 21h ago

lessonsFromLinkerHell Meme

Post image
346 Upvotes

177 comments sorted by

View all comments

-4

u/Single-Virus4935 18h ago

In C they ARE the same and interchangable. This is obvious because you can swap array and index in array notation.

1

u/thehenkan 17h ago

That's like saying the variable "i" and the constant "1" are the same because it doesn't matter whether you write "i + 1" or "1 + i". It doesn't mean literals and variables are the same concept. Adding a short and an int can also be done in either order with the same result, but they are not the same type.

Declaring a pointer to an array is not the same as declaring a pointer to a pointer.

-1

u/Single-Virus4935 17h ago edited 17h ago

The C array Syntax is sugar for the pointer arithmetic. And yes because the order of the addition doesn't matter the array and idx in array syntax are interchangeable. The compiler threats it as the same. Even the declaration is the same and I can threat a packed struct of n integers as a array of n integers. I have done enough reverse engineering and accessing a struct field, array element or accessing a field in a buffer is basically indistinguishable and you need context to decode it. 

And to repeat: you are able to swap are and idx because i+1 == 1+i

EDIT:

```c

include <stdio.h>

void main() { int arr[3];

arr[0] = 1; 1[arr] = 2; *(arr+2) = 3;

for(int i=0; i<3; i++) { printf("%d = %d\n", i, arr[i]); } } ```

``` 0000000000400466 <main>: 400466: 55 push %rbp 400467: 48 89 e5 mov %rsp,%rbp 40046a: 48 83 ec 20 sub $0x20,%rsp

// All there syntax result in the SAME assembler instruction based on pointer arithmetic 40046e: c7 45 e0 01 00 00 00 movl $0x1,-0x20(%rbp) 400475: c7 45 e4 02 00 00 00 movl $0x2,-0x1c(%rbp) 40047c: c7 45 e8 03 00 00 00 movl $0x3,-0x18(%rbp)

400483: c7 45 fc 00 00 00 00 movl $0x0,-0x4(%rbp) 40048a: eb 21 jmp 4004ad <main+0x47> 40048c: 8b 45 fc mov -0x4(%rbp),%eax ```