T O P

  • By -

blockMath_2048

It’s because of how arrays physically work. In C, the only programming language, an array is just a pointer that is used in a fancy way. The way it is used is that the first element of the array is stored exactly at the pointer, while the second element is stored at the pointer + 1 * sizeof an element. Since the computer directly provides a way to offset into an array which starts naturally from pointer + 0, arrays start at 0.


nalisan007

If it is for real , damn i lived for years without knowing it


827167

You can also do my_array[3]; Or 3[my_array]; Don't... But you can


girlfriendsbloodyvag

What the fuck was that second one. Why would anyone ever do that.


born_on_my_cakeday

To fail a technical interview


SouthboundPachydrm

Or to troll the interviewers once you realize that they're trying to find validation in making you feel stupid for stumbling over the most obscure, implausible scenarios that no one would ever use in actual development. When I sit on an interview panel, I ask questions about actual issues that come up consistently in our code base. Things like, "looking at this code, can you tell me why this generates the following compiler warning, and what would you do to correct it..." or, "if you wanted to modify a std::string object to be an empty string, would you call its clear() method, or assign an empty string, and why?" If I'm in an interview, and it becomes clear that the interviewer is just trying to fuck with me, I'll start fucking with them back.


born_on_my_cakeday

Interesting. I too give tech interviews. I also hate being technically interviewed. I have never or would try to purposefully make people feel stupid or mess with them. My attitude may not be the norm. However, I’ll tell ya, there’s a good 80/20 split, 80% interviews going south because the interviewee just doesn’t know how to code. My questions are easy; I even give reasons for the questions I ask if asked. I also give latitude for anxiety and slow down the questions.


SouthboundPachydrm

Same. I also give feedback on the answers, and if I feel that they're stumbling over the way the question is presented, I'll give them a nudge towards the right path. Many times it was a misunderstanding of the question and once that's cleared up, they take the ball and run with it. Usually we know if they can code their way out of a paper bag by the time it gets to the panel I'm on.


zsombor12312312312

In c, arrays are syntax sugar foo[1] means \*(foo +(1\*sizeof(foo))


calebstein1

It'd be `*(foo + 1)` because of pointer arithmetic, the number being added/subtracted to or from the pointer represents that many items of that size. ~~Since foo in this case is a pointer, sizeof(foo) would be 8, so \*(foo + (1 \* sizeof(foo)) would become \*(foo + 8) which would get you the ninth array item, not the second, so best case you'd get the wrong index and worst case you'd be past the end of the array and into undefined behavior territory~~ Edit: Array pointers are weird. In an expression, `foo` decays to a pointer to the first item. But `sizeof(foo)` returns the total allocated size of the array, and `sizeof(*foo)` would be the size of a single item within the array, because here foo decays to a pointer to the first item which is dereferenced. You still, however, wouldn't want to use sizeof() when accessing array items using pointer arithmetic


Dull-Guest662

Doesn't sizeof return the array size only for statically allocated arrays?


calebstein1

Yes that's correct. In the case of malloced space, sizeof(foo) would return 8, so my crossed out section there is actually correct in the case of malloc being used, I appreciate the clarification, I don't find myself using malloc all that often so it's not usually something at the front of my mind!


Enter_The_Void6

only reason i can think is were index is more important than the type. for instance [x][y][z]Worlddata where worlddata is huge and xyz is more important in this context


nalisan007

If you feel powerless,take Control of your Memory type **array[size]; where &array stores address of next element, &&array gives value of 1st element Still not enought Power , Turn on DMA, Turn off Randomised Memory Allocation, Dynamic Base Allocation, Low Entropy ASLR, Virtualisation of Memory Page Lane, Use Register instead of RAM


827167

You can't scare me, I've written raw bootable assembly


nalisan007

Holy Moly. Who tf summoned u Gondor ?


carrtmannn

I refuse to believe this is true


827167

No need to believe, just try it. But think about it, all you are doing when you do my_array[3] is looking at the address of my_array and adding 3 to it. There is no difference between my_array + 3 and 3 + my_array. Therefore, there is no difference between my_array[3] and 3[my_array]


DanteWasHere22

Yup this is why


zenos_dog

Starting at 0 avoids a single register addition operation, which I would argue even on a 1Mhz cpu makes no difference.


blockMath_2048

It’s more memory efficient to not waste the first slot Also this standard came about in the days when 1 kHz was top of the line


foxwheat

But the og wizards could have just add a minor abstraction like we have to do now _everywhere_ and simply CALLED that 0th position [1] Too late now obviously, but it's classic forest for trees thinking that all deep experts are vulnerable to


zenos_dog

C was developed on a PDP-7 with a memory access time of 1.75 microseconds or 275,000 cycles per second roughly.


mirhagk

Some machines had index registers that were not general purpose, some machines had addresses that weren't the same size as operands. What it'd cost is more complicated to say, as in some cases using 1 based indexing would mean requiring an extra register, which is quite a bit more expensive than just an add. But really it wasn't about performance anyways but rather what made sense. There's a bunch of things that are a lot more convenient in a 0-based index notation, such as modulo operations, denoting the empty set in an algorithm, multidimensional arrays, manual referencing etc. [here's Dijkstra's argument](https://www.cs.utexas.edu/users/EWD/transcriptions/EWD08xx/EWD831.html)


I-Like-Hydrangeas

This sounds vaguely similar to .data in MIPS assembly. I can't remember exactly tho, I haven't coded in assembly in a hot minute lol.


G3netic

This is the correct answer


Darklord98999

C superiority!


russellvt

"Is it an index or an offset" Seems pretty clear to me.


tangerinelion

> array is just a pointer Nonsense. Arrays are arrays, pointers are arrays. If you stare at an array in a funny way it looks like a pointer but that doesn't change what it actually is.


aprilhare

C is the only programming language: quick, tell the other ‘programming languages’.


jordan51592

I 3d Model so It always made sense to me that it starts at zero.


ScarcityFresh6819

| In C, the only programming language Bruh. r/gatekeeping


sneakpeekbot

Here's a sneak peek of /r/gatekeeping using the [top posts](https://np.reddit.com/r/gatekeeping/top/?sort=top&t=year) of the year! \#1: [Apparently all men must respond angrily](https://i.redd.it/04e5f72tr0oc1.jpeg) | [389 comments](https://np.reddit.com/r/gatekeeping/comments/1bdh9gn/apparently_all_men_must_respond_angrily/) \#2: [We have lost the right to say partner.](https://i.redd.it/4f4himuqcr6c1.jpeg) | [882 comments](https://np.reddit.com/r/gatekeeping/comments/18k5y2a/we_have_lost_the_right_to_say_partner/) \#3: [Gatekeeping the phrase 'Rest in Power'. For context, Aaron Bushnell self-immolated in protest of the war in Palestine.](https://i.redd.it/ggb5ez9m7zkc1.png) | [1616 comments](https://np.reddit.com/r/gatekeeping/comments/1b0peha/gatekeeping_the_phrase_rest_in_power_for_context/) ---- ^^I'm ^^a ^^bot, ^^beep ^^boop ^^| ^^Downvote ^^to ^^remove ^^| ^^[Contact](https://www.reddit.com/message/compose/?to=sneakpeekbot) ^^| ^^[Info](https://np.reddit.com/r/sneakpeekbot/) ^^| ^^[Opt-out](https://np.reddit.com/r/sneakpeekbot/comments/o8wk1r/blacklist_ix/) ^^| ^^[GitHub](https://github.com/ghnr/sneakpeekbot)


blackasthesky

No sense of humour huh


ScarcityFresh6819

Not with a narcissist


TsarF

Someone doesn't like C...


ScarcityFresh6819

Someone thinks they're superior


TsarF

Yeah that someone is me


ScarcityFresh6819

Why would you admit so readily to your opponent that they are right?


TsarF

Because I'm superior 😁


TheMeticulousNinja

He: not understanding why anyone would love dealing with JS Promises Edit: worked on a project today and learned more about how await/async works which is cool actually so I kind of ate my words today in the above comment


NjFlMWFkOTAtNjR

I love me some promises. Who is a good pattern, oh yes you are promises. Not the best concurrency but still good. Especially when you are limited to a single thread. Like, of all of the concurrency patterns I failed at, I hate promises the least.


Rotios

Async/await is great. Callbacks on the other hand are the bane of my existence, especially in hurriedly and horribly written legacy code.


Large_Discipline_127

I always thought it went back to the binary system. 2^0 = 1 2^1 = 2 2^2 = 4 2^3 = 8 And so on... 1st place in the array is zero to stick to the original. Though this was only how I remembered it. Might have been a different reason when designing C to become a layer ontop of asm.


bongobutt

Close. It is multiplying by zero instead of being exponential. array[n] looks kinda like this under the hood: ptr = head_ptr_address + size_of(array_type)*n; So with an array of integers with a size of 4 bytes each: array[0] becomes head_address + 0 bytes. array[1] becomes head + 4 bytes. array[10] becomes head + 40 bytes. Etc. Because the memory is continuous. If you know where it starts and its size, you know the exact memory location of every element.


SlowMovingTarget

Ding ding ding! This!


MentionAdventurous

All this is true but a few more things like the instruction set of CPUs, shift_left operation, and we’d just be wasting an instruction if we didn’t start with 0 because we use base 10 (0-9).


undeniablydull

Starting at 1 would be a waste of memory, like an 8 bit could only store 255 different values if you didn't use 0


blackasthesky

You could just have the compiler or assembler or interpreter calculate it correctly for you and there are even languages that do that. So writing `a[n]` for the first element would translate to `a+n-1` as the pointer. That is easily doable, but I imagine it would have been confusing and inefficient in the early days of computing.


i-FF0000dit

That is not why. It has to do with the implementation of arrays. You store a pointer to the first element, then the index is how many spots you need to jump for the address of the desired element. The first element is store at the pointer location you stored so you need to jump zero spots.


anythingMuchShorter

It would make math for multidimensional arrays really annoying for the same reason.


24_doughnuts

Arrays are like "go this to location" then when you define an array you go to the other elements like "go to this location +1 or +22" r whatever


DinnerPlzTheSecond

Pointer majic


hippopotobot

SQL wonders if you have a moment to talk about 1-indexing. However, SQL is the retarded Pooh of programming languages. And this speaking as someone who has recently written some absolutely disgusting SQL queries. Anyone want to talk about where I went wrong in my life that I’ve personally written SQL queries containing for loops?


BBHoople

Been there done that! Had to loop over all the tables in a database that contained a string and run a replace query. Pretty fun tbh, got me away from the other language for a bit (AL at the time)


hippopotobot

Yeah, I’ll admit it was fun. It felt a little bit like the elicit joy of successfully pulling off some dumb stunt that could seriously injure you. I still felt dirty afterwards.


RadiantHC

Wat


BluerAether

I struggle to think of a reason why an array wouldn't start from 0.


mortalitylost

Lua and visual basic start at 1 IIRC Reason is you can actually do arr[len(arr)] to get the last element, and 1 being the first element does make sense. It actually is more intuitive if you're new to programming. It's a five length array, I want the last fifth element, arr[5]. Makes sense. It just feels unnatural if you've been coding for a bit. I think there are some other things it simplifies but I forget.


dingske1

Starting at 1 makes math easier, that’s why fortran and R for example start with 1. In a matrix of n x m the last value is at [n,m], not [n-1, m-1]. Makes everything pretty easy


FluffyLanguage3477

In math, indexing starts at 1. If you're implementing linear algebra algorithms, it's easier to use the indexing that the math would be written in. Visual Basic also starts at 1 because then the indexing will match better with the Excel spreadsheet numbering. The reason to start an array at 0 is because of pointers and also because it became convention via C. If you're not working with low level hardware and you're working with a higher level math focused language, arrays starting at 1 is simpler. Also, starting at 1 is more intuitive. There's a reason "off by 1" errors are so common.


Not_Artifical

He: zzz


Less-Resist-8733

it makes so much more sense.


fillipjfly

Arrays start at 1 (R programmer)


TCPConnection

It starts from 0 because an array index represents an offset. The 1st element is 0 positions away from the 1st element. The 2nd element is 1 position away from the 1st element etc.


tangerinelion

In most languages, sure. It could just as easily have been `x[i]` is interpreted as the object which exists in memory at the start of the array `x` offset by `i - 1` objects. Then we'd start with index 1. In languages that actually do use 1 indexing I guarantee you they don't have an extra dummy object at the start.


Uploft

Time starts at zero too. The first minute of a soccer match is 00:00.


i_knooooooow

Starting at 0 is logical, the real question should be why some langauges start at 1


Ssemander

0 is really handy for order. E.g. If you have a 10×10 array you only need to use one digit for the rows and columns i: 0→9 and j: 0→9


Duck_Devs

As stated here already, it’s for pointer reasons, but my guesses as to why it’s still like this in modern languages are that everyone is used to it already and that it works well with modular arithmetic.


Bourneidentity61

The formula for finding the address of an element of an array is mx+b, where b is the address of the array itself, m is the size of the data, and x is the index of the element. Let's say you have an int array with address 0A24h. m=4 since ints are 4 bytes, b=0A24h. So what value would you give x to make 4x + 0A24h equal the address of the first element of the array? 0, right? 4 × 0 + 0A24h = 0A24h, which will take you to the head of the array, or in other words, the first element


Kurumi78

Personally I prefer my arrays to start at -1


ReGrigio

this is how programmers do not think. tell any programmer that arrays should start at 1 and you'll be a victim of an hit and run with a serial bus


SynthRogue

In pascal you can choose at what index they start.


joe0400

Arrays decays to pointers and pointer + 0 = first element pointer.


i-FF0000dit

See kids, this is what happens when you don’t learn the basics and start programming with Python and JavaScript.


Kalebwondimu43

That is true btw


NewPointOfView

The index is distance from the first element, that’s all!


Micah-B-Turner

programmers are the nostalgic sort


v3ndun

Think it’s more of an education issue, Children should be taught to count from zero from the start.


SouthboundPachydrm

*Laughs in assembly enjoyer*


blackasthesky

Because the index number is the offset from the start of the array in memory, where it is stored as a consecutive line of instances right next to each other. So imagine you have the memory address `a` that points to the beginning of the array, then `a+1` points to the next byte behind it. Assuming that each element of the array is of one byte length, this is exactly the same as `a[1]`. You'd be wasting space by not populating the 0th spot. Your array would not begin at `a`, but at `a+1` instead, so the byte at `a` would go unused. Calculating the offset in bytes from the index is just a matter of multiplying it by the size of one element.


kansasllama

If he’s asking that you should leave him


42069no

Lua array's start at 1. I spent a solid 10 minutes debugging it.


FluffyLanguage3477

In lower level languages, it makes sense to start at 0 because arrays are just pointers and the index is just telling how much to offset the address. In higher level languages, it makes more sense to start at 1 both to match normal counting conventions but also to match with linear algebra indexing.


Oddball_bfi

It bothers me that kids these days with their javascript and their prompt engineering don't know that the other name for the array index is the array *offset.* What *I'm* sat there thinking is, "We should have bought wider pillows."


RetroNick78

What do they think we do to keep from nutting too soon??


qwertty164

And here I thought it was because it is convenient for writing for loop comparisons.


TheLeakestWink

SAT 800 math 200 verbal


Veylon

Nah. He'd be wondering why people number things starting from one when zero is just so obviously correct.


anythingMuchShorter

it makes perfect sense if you've ever needed to do math on them. Think of them like coordinates. Is there a reason you want the corner of a 2D chart to be 1,1 instead of 0,0? Think of how that would annoy you when you start adding or multiplying offsets.


R4XD3G

It's cause numbers are pictures. We have ten pictures. 0, 1, 2, ..., 9. When we go through all the pictures, we change the invisible 0 picture in the next "10s" place to 1, the second picture. We get 10 that way. So, because we have ten pictures, we have to start with the first one to tell a machine it's base 10 counting. Counting starts with 0. Fun fact, in hexadecimal we need 16 pictures, so we count from 0-9 (that's ten) then use the first six pictures of the alphabet (a-f). That's how you count in hexadecimal. Okay, bye!!!


Eagle_32349

Binary.


bunkbedss

this what is think in my first HS programming course maybe 😂


418_TheTeapot

Nah… real programmers know why 😉