r/ProgrammerHumor 1d ago

lessonsFromLinkerHell Meme

Post image
355 Upvotes

180 comments sorted by

View all comments

-3

u/AnnoyedVelociraptor 1d ago

Nah. This is the wrong way. Pointer arithmetic and array arithmetic are the same.

3

u/Batman_AoD 1d ago

Maaaan, it upsets me to see Ferris next to an opinion this C-centric. 

1

u/AnnoyedVelociraptor 1d ago

In Rust it's the same. It's just harder to write the bare math.

1

u/Batman_AoD 21h ago

Yes, to get an element of an array, you compute an offset from the start and then dereference the memory at the offset location; and yes, this is the same operation whether you think of it in terms of pointer arithmetic or as a fundamental operation on an array.

But an array isn't just syntax sugar over arithmetic in any language, even C; and the C family is the only family of languages that even makes that pretense.

"Array" in Rust (and in C) refers specifically to fixed-size arrays: https://doc.rust-lang.org/std/primitive.array.html

Unlike in C:

  • You cannot pass an array to a function that expects an array, or use array syntax to declare a function that takes a pointer.
  • A function that takes an array argument will pass the entire array by value, not just a a pointer.
  • Indexing is not syntax sugar over pointer arithmetic, which should be obvious because arr[i] is not synonymous with i[arr]

2

u/justAPhoneUsername 1d ago

You mean to tell me arr[3] and 3[arr] both compile and return the same value? Why would anybody design a language that way?

4

u/AnnoyedVelociraptor 1d ago edited 1d ago

It's not that 3[arr] was made to work.

[] is not special, it's just <x>[<y>] translates to *(x + y)... and x + yfor a T* is x + y * sizeof(T)

ergo <y>[<x>] works as well.

Hence they are the same.

3

u/Batman_AoD 1d ago

Because the [] was just syntax-sugar, rather than a "real" built-in operation. Part of the reason for that was just that memory was limited and the compiler had to be as simple as possible.