r/ProgrammingLanguages • • 10d ago

Help Should I choose 1-based indexing or 0-based indexing for my programming language?

I'm creating a host-embedded, minimal, beginner-friendly programming language as a replacement for Lua. This language is really human readable, English-like and beginner friendly, with automatic memory management, automatic parallelism, a fantastic and helpful compiler inspired by Rust, and other things. The biggest question I have is whether I should choose 1-based indexing or 0-based indexing?

29 Upvotes

232 comments sorted by

140

u/willbdb425 10d ago

You could be the first language to start from 2

34

u/iamevpo 9d ago

Or -1! We need innovation

8

u/iamevpo 9d ago

And going backwards.... -1, -2... -n

2

u/Magic_music 7d ago

shoutout to the perfect programming language lol
would still be innovative though

5

u/nextCosmicBuffoon 9d ago

Yes, let's even use "B", and for fun array indexes are always given in base-13.

2

u/Minecraftian14 4d ago

We already have Excel

262

u/knue82 10d ago

How about a compromise and start with 0.5?

14

u/Available_Safe1818 10d ago

Or he could index with p-adic numbers.

48

u/Seek4r 10d ago

Yep

The idea of indexing with 0.4999999997 just floats so well!

33

u/Mistigri70 10d ago

0.5 can be represented exactly by floats because it's just 1*2-1

9

u/AustinVelonaut Admiran 10d ago

Plus, float-indexing could be used to perform linear interpolation between two array elements!

3

u/mentalAgnostic 6d ago

that's ridiculous, obviously we should be treating arrays as splines

1

u/Character_Score7776 5d ago

I suggest we make it configurable. Not at a type, of course, but as a random free function called "setInterpolation()".

2

u/pulse77 9d ago

He should have a built-in treshold, so that 0.4999999997 is interpreted as 0.5... THAT would be something new...

1

u/L8_4_Dinner (Ⓧ Ecstasy/XVM) 7d ago

That was the Pentium FDIV

→ More replies (5)

5

u/Weebs 9d ago

Honestly I did consider making Index a separate numeric type and indexing is controlled by a trait that is 0 based for int and 1 based for Index

I can make everyone unhappy! :)

3

u/sciolizer 10d ago

As an added bonus, you have a clear way to distinguish "index to a cell" from "index to between two cells"

3

u/deaddyfreddy 6d ago

start with 0.5?

liters of beer? Sure!

3

u/casce 5d ago

I feel like it needs like 0.5 barrels to come up with such an evil idea

2

u/Linuxologue 5d ago

Once in germany my mother in law ordered a 0.5 and as a stupid swede I thought that was a beer with 0.5 percent alcohol.

But not in Germany. It's a half litre full strength beer.

1

u/deaddyfreddy 5d ago

Were you 16 or so?

1

u/Linuxologue 5d ago

Not sure how that is related but no I wasn't 16, I was just stupid :)

→ More replies (2)

2

u/ar34m4n314 6d ago

Also, why constrain ourselves to indices that are consecutive integers? Why not, say, the Fibonacci numbers starting with the 2nd 1? Or the primes?

1

u/prehensilemullet 5d ago

Like pixels.  0, 1 etc represent the lines between pixels, the pixels are actually centered at 0.5, 1.5 etc

141

u/reflexive-polytope 10d ago

The friendliest thing you could do for a beginner is teach him or her to count from 0 as early as possible.

51

u/SquarePixel 10d ago

It’s actually not a count. It’s an offset. Moving the cursor by zero leaves you in the first slot.

3

u/No_External7343 5d ago

It is only an offset if you think of arrays as syntactic sugar for pointers.

4

u/SquarePixel 5d ago

Typically arrays are contiguous blocks of memory, but I take your point, in a higher level language an array could just be an ordered sequence, and the index can mean "which element?".

2

u/reflexive-polytope 9d ago

I'm sorry, but... The smallest possible cardinality of a set is 0. The smallest possible dimension of a vector space is 0. The smallest possible degree of a term in a polynomial is 0. And so on.

The only setting I can think of where 1 is the natural starting place is multiplicative number theory (Dirichlet series!), but in that setting you're more interested in decomposing a number into factors (cf. the formula for the Dirichlet convolution) than into summands.

For things that increment additively, 0 is the correct starting place.

23

u/hairytim 9d ago

I think you misinterpreted what they were saying. When people say “it’s not a count, it’s an offset”, they are arguing in favor of starting at 0.

The initial offset is 0: you are distance 0 away from where the sequence started.

0

u/reflexive-polytope 9d ago

I count from 0, in the sense that 0 itself is a valid count!

0

u/[deleted] 9d ago

[deleted] — view deleted comment

5

u/freshhawk 9d ago

yes? i do notice that i have no apples in my basket, that's why i went to where the apples are, i started at zero

3

u/Karyo_Ten 9d ago

I count building floors from 0

3

u/reflexive-polytope 9d ago

When you count informally in daily life, counting from 1 has the intuitive benefit that the index of the last element is the size of the collection you're enumerating. You detect that you have reached the end of your enumeration because visually there are no objects left to enumerate.

When you count formally in a program, however, counting from 0 has the technical benefit of making the counting state machine and its associated proofs actually pleasant to work with.

A state machine has no “eyes”. It can only detect that you have reached the end of the enumeration because there's no element at the position given by your current index. If you count from 0, then the index where you find no element is the size of your collection. If you count from 1, then the index where you find no element is one past the size.

These things should be obvious!!!

6

u/SquarePixel 9d ago edited 8d ago

Again you’re describing offset-based indexing and calling it “counting”.

When someone counts apples, the count is understood to answer “how many”. It could be 0, 1, 2 or more. That’s still counting from zero. Zero means no apples.

Likewise, array length answers “how many.”

→ More replies (2)

8

u/SquarePixel 9d ago edited 9d ago

Counts can start at 0, but that’s about how many elements there are, not where they sit. An empty array has a count of 0. Once it has one element, the count is 1, and that element is at offset 0. That’s why the last element is always at count - 1.

I know I’m being pedantic, but thinking of the index as an offset clarifies why indexes start at 0.

1

u/casce 5d ago

That’s why the last element is always at count - 1.

I agree that's a great convention (especially in higher level languages) but this is neither as intuitive nor as unambiguous as you make it to be.

Because if it is an offset, "-1" would one the element before the array in memory and lower level languages tend to interpret it that way and you will land out of bounds.

Not disagreeing with you, just saying people should be aware. -1 being the last element is a convention of some programming languages but does not come naturally and is not always the case.

→ More replies (6)

1

u/CompetitiveSpot2643 5d ago

you can have a projection subspace of dimension -1 which is also a vector space though

1

u/reflexive-polytope 5d ago

The dimension of a vector space is by definition the cardinality of a basis. No way for that to be -1.

1

u/CompetitiveSpot2643 5d ago

projective subspaces have a different notion of dimension, related but not equal to the cardinality. they are still vector spaces though

→ More replies (3)

28

u/sciolizer 10d ago • Bravo

Kind of joking but kind of serious:

I want to see a language that takes seriously the idea that offsets and sizes are different types of numbers. Just because there's an easy conversion between them doesn't mean they are the same type.

For instance, the "Size" type should have a "last" method that returns a value of the type "Index". Whether the "last" method subtracts 0 or 1 is going to depend on whether you are using 1-based or 0-based indexing, but code that constructs Index values only by calling methods on Size values and other Index values will not need to care. Its behavior will be correct regardless of how things work underneath.

8

u/matthieum 8d ago

It's something that's pretty interesting when thinking about "coordinates".

It feels weird for space, but just think about time: clearly Instant & Duration are very different things! An Instant is a point in time, whereas a Duration is a "vector" in time.

It makes no sense to add two Instants -- what is the result of adding Jan 1st, XXXX to Feb 2nd, YYYY? -- but it makes sense to add a Duration to an Instant, and subtracting two Instant naturally gives a Duration.

The analogy point/vector is not perfect for Count/Index -- it does make sense to add two Counts together -- but I do agree that Count & Index have a different nature.

3

u/sciolizer 8d ago

I think the analogy to space works perfectly:

  Point | Vector
--------+---------
Instant | Duration
--------+---------
  Index | Count

Though perhaps is would be better to call Count something like "Shift" or "Range"?

I'm sure there's some mathematical structure that captures this idea, like maybe an Affine Space?

1

u/ExplodingStrawHat 7d ago

Yup! Affine spaces are indeed what you're thinking of

1

u/matthieum 7d ago

Oh! I see! For some I equated Count w/ Instant, and it didn't work at all.

I think Offset would work for Count -- offsets can be negative, notably -- though it feels a bit weird for len() to return an "offset" :)

4

u/WittyStick 9d ago

That's essentially what iterators are for.

SomeCollection foo;

for (auto it = foo.forward_iter.begin(); it != foo.forward_iter.end(); it = it.next()) { ... }

foo (auto it = foo.reverse_iter.begin(); it != foo.reverse_iter.end(); it = it.next()) { ... }

1

u/esotologist 7d ago

1

u/sciolizer 7d ago

Depends. Does foo.size() == 1st compile? If so, then no.

Also, how does you idea work with non-literals, e.g. foo[i]?

2

u/esotologist 7d ago

No they're different types. 1st is an ordinal not an integer. It's a bit like comparing a range to an integer. 

foo[i] works as you'd expect depending on the typing of i. 

19

u/pslgz_ 10d ago

Go with the letters

12

u/No_Engineering_1155 10d ago

Oh no, excel enters the chat

33

u/jmtd 10d ago

0. If you’re going to be integrating into other systems, they almost certainly count from 0. 

10

u/ComradeGibbon 9d ago

There is the whole issue where people may want to translate code from another language to yours and having differences in array indexing is a real pain in the ass.

Gives lua the stink eye.

3

u/jmtd 9d ago

Another example: neovim’s lua api. Since it wraps existing vim functions some things return or accept indexes from 0, and others from 1. Even more fun is when you are dealing with coordinates (eg screen row/columns) where each side of the pair is using a different one. 

50

u/latkde 10d ago

The canonical reference on this is Dijkstra's memo EWD831 Why numbering should start at zero. He argues that ranges should be denoted as lower bound inclusive, upper bound exclusive, and that elements should be indexed by the number of elements that precede them. The first element is preceded by zero elements.

The argument has been highly influential, and all modern programming languages except for Lua use 0-based indexing. (A handful of more exotic languages allow variable-offset indexing on a per-array or global basis, e.g. Julia or Perl).

Sometimes in programming language design, we try to do the most natural thing – trying to design a language that works just like mathematical notation, or a language that reads just like natural English language. But this intuition can obfuscate that programming languages are precise formal languages. They need clear rules for writing, and they form important tools for thought and design work. In the end, the code is the only true representation of the software design, so PLs should pick syntax and semantics that make it possible to clearly express the design.

This is arguably even more important for beginner-oriented languages. In this context, I actually like that Python is indentation-sensitive, because this forces the programmer to clear up their thoughts about how different statements relate to each other – I've all to often seen fledgling programmers be baffled about the effect of simple if-statement because they confused themselves through inconsistent formatting.

A big step to reduce confusion is to avoid unnecessary innovation. If most languages have settled on a good way of doing things, do the same. For example, method calls and object attribute accesses now universally use a dot ., other syntax like arrows -> has effectively died out. Things are similar with array indexing. The syntax is now almost universally array[index], and indices are universally zero-based (except for Lua). If you want to do something different, you should have very good reasons.

That you envisage a migration path from Lua may be a good reason, but unless your language is effectively a Lua dialect so that most code can be copied without any semantic changes, I personally don't think that reason is good enough.

20

u/Weebs 9d ago

"The argument has been highly influential"

it has and it's always been strange to me because I never found it convincing, it was one of the only things I've read from him I didn't really care for. I don't mean to say 1 or 0 is right, but the memo didn't change my thinking about it

8

u/Nprism 10d ago

the other exception is MATLAB

19

u/personalityson 10d ago edited 9d ago

The other exception is all languages used in math/statistics: Fortran, R, SAS, SPSS, Stata, Matlab, Mathematica, Maple, Julia, Scilab

Is there something mathematicians got wrong about matrix indexing? Hurry up and send them a message

1

u/L8_4_Dinner (Ⓧ Ecstasy/XVM) 7d ago

Both users agree.

-1

u/nybble41 9d ago

It's not wrong per se, just awkward. The conventions for matrices were determined before zero was considered a natural number. If they were doing it over today they would probably start from zero like everyone else.

2

u/ParsingError 9d ago

BASIC is also an exception and Visual Basic .NET handled it via a weird hybrid approach where array dimensions are specified as an inclusive upper bounds, but the lower bound is 0, so Dim numbers(4) as Integer gives you an array with 5 elements numbered 0 through 4.

1

u/DerekRss 6d ago

QB1 to VB6 used DIM numbers(0 TO 4) AS INTEGER or DIM numbers(1 TO 4) AS INTEGER, depending upon which you wanted.

2

u/ParsingError 6d ago

Strangely enough, the .NET CLR supports non-zero-based arrays, but they are not syntactically supported in VB.NET. (They can still be created with Array.CreateInstance though.)

1

u/DerekRss 6d ago

Yes. It made conversion from VB6 to VB.NET more painful than otherwise necessary. My guess is that they did it that way to retain easy convertibility into C#. Too bad for all the existing VB6 code!

1

u/Cold-Armadillo-154 10d ago

Man i hate MATLAB

5

u/apetbrz 10d ago

Hasn't the -> notation only "died out" because most languages don't require the programmer to care about pointers? Languages that use raw pointers still benefit from including it, I wouldn't call it some "innovation" so much as a shorthand for the uglier alternative of (*foo)., which can be relevant.

5

u/kohugaly 9d ago

Languages that use raw pointers still benefit from including it

No they don't. Raw pointers typically do not have methods of their own, so ptr.method() can simply automatically dereference ptr as much as necessary until it finds type that actually has method declared.

2

u/apetbrz 9d ago

What language does this? It seems like poor design for a language to both allow the programmer to manage raw pointers, and to make assumptions regarding dereferencing those pointers on the programmer's behalf. I'd expect one or the other.

5

u/StaticCoder 9d ago

1

u/apetbrz 9d ago

Haha, I somehow missed that, and I love that language.

→ More replies (3)

1

u/xsrvmy 5d ago

Can you actually do that on unsafe pointers, or is it on references only?
I don't believe C++ references require `->` either.

2

u/kohugaly 4d ago

In the languages I'm familiar, that have both pointers and references, the dot operator only works on references.But that is deliberate choice of the language designers. The semantic difference between raw pointers and references is not relevant to whether you could implement the dot operator on raw pointers too.

4

u/kaplotnikov 8d ago

If we continue zig idea further, navigational syntax for pointers makes more sense. Instead (of (HANDLE)(&((*foo).field)) to use foo.*.field.&.(HANDLE) where .* , .& and .(type) are suffix operators with the same precedence as dot. Then -> is just combination of .* immediately followed by .. IDE should like such syntax as well.

13

u/personalityson 10d ago

Pseudo-scientific memo pretending to have something to do with math

Etc etc, Dijkstra's main argument is: "that is ugly"

3

u/prehensilemullet 5d ago

I like 0-indexing except when a library numbers months from 0-11

2

u/Reasonable-Rub2243 9d ago

I liked Mesa's solution to the inclusive vs. exclusive range issue: indicate it using standard mathematical notation.

[0..10) - first index 0, last index 9

[1..10] - first index 1, last index 10

Yes this breaks paren matching commands in editors. It's so pretty though.

4

u/latkde 8d ago

The huge drawback is that this sacrifices the []() symbols for range notation, which makes it tricky to also use them for other purposes. Yet another example of mimicking math notation beyond what may be suitable in a programming language. In practice, one of the less objectionable range syntaxes I've seen is Rust's 0..excl and 0..=incl.

1

u/FooeyBar 7d ago

I use tilde and equals for my ranges, independent of braces: array[0~9] or array[~=8]

3

u/L8_4_Dinner (Ⓧ Ecstasy/XVM) 7d ago

We did this in Ecstasy until we saw the `x..<y` syntax in another language and stole it.

1

u/ReddyKiloWit 6d ago

Raku uses an exclusion operator for a similar effect: [0..^10] = stop at 9, [3^..^10] = start at 4, stop at 9, ^7 = short for start at 0, stop at 6. ( ['a'..^'i'] gives you 'a' to 'h'.)

1

u/kyr0x0 6d ago

You can still design a human targeted language and lower to formally correct notation. It's just a pain in the a..

1

u/resignresign1 5d ago

julia uses 1 based indexing and i liked it

1

u/CarEnvironmental2558 4d ago

I followed your link to Djikstra's paper and I'm super intrigued by it, because it seems:

- wise and reasonable
- tightly argued
- poorly written and strangely chatty
- extraordinarily short

Is this combination of attributes common among historically influential computer science papers?

1

u/latkde 4d ago

That Dijkstra essay is just a hand-written note, not a peer-reviewed paper. The EWDs were passed around and photocopied by colleagues, but not formally published. Think of it more as a blog post. Wikipedia has a paragraph about them: https://en.wikipedia.org/wiki/Edsger_W._Dijkstra#EWDs

Many things have become influential in the computer science / software engineering world despite not being academically rigorous – also due to lots of innovation happening outside of academia. It's necessary for readers to distinguish between style and substance themselves. I find that many older papers (e.g. from the 70s/80s) would not meet current academic standards, but there was way less publication activity back then, and the few articles we still talk about have stood the test of time.

28

u/bobam 10d ago • Bravo

Why choose? Pascal lets you pick:

arr1 : Array[-5..5] Of Integer;

8

u/alaricsp 10d ago

One of the few aspects of Pascal I miss. The enum type and "Set of <enum type>" thing was cool too.

5

u/mamcx 10d ago

YES!

In fact, I think that "index" is 100% a domain type, for TablaM that follow the relational idea I see a[0] as SELECT * FROM a LIMIT 1, and then from array langs:

days = [monday, .., sunday]

let first = days # 0 
let rest = days # [saturday, Sunday] // # is indexing
let rest = days # [5, 6]
let work = days # monday..saturday 
// All sugar for:
let work = days ?where Range(monday, saturday)

1

u/Rechenplaner 7d ago

The idea is compelling. Quite often, you only want to allow specific indices anyway, which usually forces you to fall back on a hash map structure in the language you’re using. In this case, it would be purely a matter of syntax; "cosmetic" sugar that the compiler could optimize away into direct arrays. By injecting a bit of "code magic," the compiler could handle the index translation beforehand, sparing the programmer from having to do it manually.

1

u/21Ali-ANinja69 7d ago

Yeah, this is the way

19

u/sooper_genius 10d ago • Bravo

The reason C started using 0-based indexing because it was a count of an offset from a pointer to memory, not really an index. People naturally start indexing from 1.

Trying to mix offsets and indices can be a problem. You have to often think whether you have to add or subtract 1. If you're adding a string of length 2 to another one to length 3, what is the offset of the last character? Not 2+3 = 5, but 2+3**-1** = 4. But the length of a snippet of a string length 6 from 2..5 (inclusive) is 5-2+1 = 4. Javascript uses a slicing method .slice(2, 6) for this where char offset 6 is not included-- 2..6 where 6 is not included.

Using offsets can make such calculations easier and more consistent, but where you add or subtract 1 is a pattern you have to get used to.

-2

u/nybble41 9d ago

Indexing starts with the first natural number, so whether you index from 0 or 1 depends on how you define the natural numbers. The modern definition (formalized as ISO 31-11 in 1978, though precedent dates back to the 1800s) says that 0 is a natural number, so indexing should start with 0. Some older definitions omitted 0 from the natural numbers, so their indices would start with 1.

7

u/sooper_genius 9d ago

When people talk about a list of things, they order them as first, second, third, etc. These correspond to 1, 2, 3. This is what I meant when I said that people naturally start indexing from 1, not really relating it to the formal definition of natural numbers.

If a computer language is "beginner friendly" it could be best to start with indexing at 1-- especially if pointers and offsets from pointers are Not A Thing in the language. As big a joke as it is, having lists start at zero, no culture naturally does this outside of technical contexts.

While I agree that starting at zero makes some concepts easier in a language, it is a mental leap to say that the first item #1 starts at the zeroth offset, therefore we'll number it #0. If I have three things, the last one is #2. This is mentally disconnected unless you have the training to see what is happening. Very few five year-olds will raise their first finger and count "zero".

14

u/hglman 10d ago

0 is an offset, 1 is how you count. 

6

u/Xandaros 6d ago

I've done a decent amount of work in Lua and let me tell you, the 1-indexed nature of it is an absolute pain in the arse.

It's fine if you just want to access at a static index, or iterate over them, or already have an index from somewhere. It doesn't matter where your indexing starts, then. But as soon as you need to calculate an index, especially if that calculation involves modulo, you are going to be adding and subtracting 1 all over the place to make that work.

Go with 0-based.

1

u/spaceLem 3d ago

Julia gives you the mod1 function for exactly that case. Other than that, I've found I hardly ever do manual indexing in 1-indexed languages because they provide the tools to do that automatically.

16

u/runningOverA 10d ago

New languages start with 1 based indexing, as that "makes more sense."
After a few version they support both.
Then goes back to 0 based indexing after a major reboot.

9

u/woppo 9d ago

Example?

5

u/joakimds 9d ago

Study the Ada programming language. When creating a new type for indexing it is the user who defines the range. You may find that inspiring when creating a new language.

9

u/Key_River7180 Nain. 10d ago

0, make them a favour

8

u/ultrasquid9 10d ago

the easiest answer: both.

arrays have a .nth method which is 1-based, and a .offset method which is 0-based (bikeshed the names as you see fit). save square brackets for something else, e.g. generic parameters. indexing isn't common enough to need its own syntax.

8

u/esotologist 7d ago

I've thought of a neat way to do both in my language.  Use 0 indexing with digits and 1 indexing for ordinals. 

array[0] == array[1st] or array.0 == array.1st

1

u/Orbidorpdorp 6d ago

2

u/esotologist 6d ago

Thats in most programming languages I know. I don't think there's a second or third value as well though right?

18

u/EggplantExtra4946 10d ago edited 10d ago

0-based, it shouldn't even be a question. Lua sucks.

Every time this comes up people say that in real life people count from 1 (even if it's often true it doesn't matter) but there is a good counter example. Some people decided 2026 years ago to start counting years at 1 (to be fair the number 0 didn't exist I think) and theoretically centuries and millenias should start at xxx1: 101, 201, 501, 1001, 2001 but in practice everybody says fuck that: 1800, 1900 and 2000 are the first year of their corresponding centuries and millenium.

4

u/chibuku_chauya 9d ago

Even the counting from 1 in real life thing only goes so far. I was taught to count from 0 as a kid at school, not 1. Must have been a curriculum quirk.

4

u/Automatic-Tackle5018 10d ago

"Should array indices start at 0 or 1? My compromise of 0.5 was rejected without, I thought, proper consideration." -- Stan Kelly-Bootle

12

u/SecretlyAPug 10d ago

0 indexing is really not that hard for beginners to learn, and learning 0 indexing will make it easier for beginners to pick up literally every other programming language. all 1 indexing does is get beginners used to a different system with no benefit, and frustrate nonbeginners who are used to 0 indexing.

6

u/Inferno2602 10d ago

I've always personally prefered 1-based, but the convention has settled on 0-based and doing something else needs a strong reason

6

u/Diffidente 10d ago

I wouldn't call it just a "convention", from a memory/assembly pov is quite obvious why we start from 0. Historically it was much later on that newer high-level languages abstracted the memory away and got the leasure and leeway to start from 1.

9

u/Inferno2602 10d ago

It's absolutely just a convention stemming from the popularity of C. Some of the earliest languages to feature arrays, Fortran, Algol, COBOL, etc... All used 1-based indexing and all predate C.

0

u/Diffidente 10d ago edited 10d ago

The languages you mention had specific purposes and were designed to be rather high-level. Perhaps Fortran is the only one closer to C.

C was designed to become kind of a common ground between different architectures and to map efficiently to their instruction-sets and to memory.

I' m currently interviewing for Qualcomm, writing a bunch of C, looking at memory and assembly dumps. I can't even fanthom how I would deal with memory having arrays starting at 1.

→ More replies (2)

6

u/Comprehensive_Chip49 10d ago

The language could randomly choose whether the starting index is 0 or 1, varying from one compilation to another.

3

u/Available_Safe1818 10d ago

You could make the index range defined with the array iteself.

5

u/freshhawk 9d ago

Zero, definitely. Even though it's not the normal starting place for ordinal counting, and that's what we think of as "normal numbers".

But natural numbers start at 0, and everything else in the language will be zero-start-flavored. Everything in programming is trees and the size of the first layer is node-size ^ 0 == 1, the second layer is node-size ^ 1, etc. If you have multiple shapes of data structures the lengths and sizes and ways they can combine will be numbers that start from 0. If you're dealing with choices then the number of choices you have to consider will be numbers that start at 0.

If your language is very specialized for indexing flat homogenous arrays without much math being done on those indexes, or counting apples, or identifying what place people came in in a race then maybe choose 1. There will be weird mismatches sometimes, having to decrement/increment during some easy math options and it's annoying, but adding to the end of an array by hand is elegant and terse.

Or, use 0 and everything works nicely except that adding a new thing to the end of an array is setting index count(a) + 1 and it feels like it being count(a) would be more elegant.

So how much are you writing loops that insert to the first open slot in an array and not doing something at a higher level of abstraction, but don't want the numbers to work with memory/pointer type math because you aren't at that low level. Feels like a thin margin where it makes sense. I guess Lua kinda fits here honestly, at least it's defensible that Lua chose this by my own argument.

4

u/Jbolt3737 9d ago

0 based, please, it may be weird for new new programmers but anyone who has written like any amount of code would like it to be 0 based

2

u/grimonce 10d ago

Use 6 based Indexing

2

u/DrunkHacker 10d ago

Call them offsets and base at 0?

Kinda serious. Take a string, what’s the first offset character in the string “abc”, and everyone knows it’s ‘b’. What’s the first indexed character in the string “abc”, and both answers could be justified.

Of course, they’ll later learn that programmers use the word index to mean the same concept. But it may help the mental mapping for 0-indexing that early students struggle with.

It’s also historically correct. You’d have a pointer and then an offset to a memory address corresponding to an element in an array.

2

u/gabedamien 10d ago

Half-trolling, half-serious: make your `at` method polymorphic with an Indexable typeclass constraint, and able to take statically typed Ordinal or Offset numbers, but not raw numbers. The only way to construct Ordinal or Offset numbers is with explicit constructors/conversions and normal Int-taking funcs refuse them at compile time, so it's impossible to have off-by-one errors, at least insofar as 0- and 1-indexing cannot be guessed wrong.

2

u/nextCosmicBuffoon 9d ago

Do you think you'd be doing beginners a favor by teaching them that the first index of an array is 1?

2

u/bcardiff 9d ago

Like Prolog, you can allow the callsite to decide. There is a nth0 and nth1 operation that treat indices starting in 0 or 1.

2

u/TheRealUprightMan 9d ago

A zero based index makes pointer math easier. The index is the offset. It also means your loops are the simpler < size rather than <= size. However, if you are storing the array size as element 0, then a 1 based index would always access the correct value, and getting array size is index 0. So, there are valid reason for choosing 1 over the other. It depends on how you handle arrays internally.

2

u/outofsand 6d ago

Read Dijkstra's "Why Numbering Should Start at Zero" before making any dumb decisions.

5

u/AdreKiseque 10d ago

0. It's the standard and Lua's departure from it is arguably the biggest reason one should want to move away from it to begin with.

-2

u/MCWizardYT 10d ago

C uses 0 + a number as an offset. Lua just gives you the actual index. So that's why it starts at 1. I do agree that it can be confusing since we're so used to using the 0 + offset rule, but Lua's way had its place

3

u/personalityson 10d ago edited 9d ago

Allow arrays to start at ay index

Arr(-5 to 5)

0-indexing is not array indexing, it's offset from the first element/pointer, basically it's memory arithmetics, it denotes where the segment starts. Makes sense when doing low level programming or working with near-"continuous" measures, like memory bytes: a segment of n bytes starts at byte x etc. This has nothing to do with indexing elements of the array you are working with.

1-indexing is counting how many complete segments.

1

u/RayNbow 9d ago

Allow arrays to start at ay index

Arr(-5 to 5)

As someone who started with Visual Basic a long time ago, yes to this.

3

u/bdowns328 9d ago

Your language, your choice. Go with what you like most. But most languages use 0 and makes things easier when new users come to your language.

5

u/adamrichardlimb 10d ago

Zero, the whole idea behind zero indexing is your list starts at memory position 12345. Then 12345 + 0 is the start of the list. If you want the next element then it's 12345 + (1 x size of an item). 

The index is actually the amount you multiply by to find the l osition in memory your element starts at.

While it's easier for people to start using lists with 1-indexed, if you truly want people to learn programming, they have to learn about memory at some point, you are only making that harder for them with 1-indexed.

3

u/personalityson 9d ago

Make a choice: are you indexing memory or array elements

0

u/adamrichardlimb 9d ago

False choice - in programming, indexing an array is indexing memory. If the zeroeth element is also the position in memory plus zero, that's harmony we get for the small cost of having to mentally start at 0 and not 1. It's also where the standard came from.

1

u/personalityson 9d ago

True array index is a key. Offset is something hidden from the user. If you're working with array offsets directly, your arrays dont have indexing to begin with, you have a block of memory

1

u/adamrichardlimb 9d ago

Just because an offset is hidden from the user, doesn't mean it is not an offset. When we do items[index] in C, that is syntactic sugar for memory position of items 

  • (i ndex * sizeof(Item)). That's what every computer is ultimately doing under the hood with every array.

You can argue that it's possible to just index to a position halfway through that list, but now we're just arguing about languages and list implementations, not if an index is an offset.

1

u/personalityson 9d ago

(i ndex * sizeof(Item))

You are committing representation exposure, ie. a machine detail leaking into the language

→ More replies (1)

3

u/TiddoLangerak 10d ago

This is not a great reason though to use 0-based indices. In very few languages does the programmer need to care about memory position, even modern day low-level languages completely abstract that away.

Don't get me wrong, I still think that generally 0-indices are better, but that's largely based on Dijkstra's arguments, which are actually relevant for the programmer.

2

u/adamrichardlimb 9d ago

Firstly I agree with Dijkstra's arguments and think they're stronger than mine.

However, I will say that all programming languages ultimately do deal with memory, regardless of how abstracted away it becomes because programming just is, by its nature, using memory.

Programming languages should probably account for the fact that many of their users will move onto other languages, and may wish to go more low-level. That's not a reason to exclude something like a garbage collector which is a huge utility for those who choose to use it, but when we're talking about the trade-off between 0 and 1 indexing, I think deliberately choosing a less common convention just because it's more intuitive is a bad trade-off when the work to remember to zero-index is about two weeks of programming practice.

→ More replies (1)

0

u/BiedermannS 9d ago

That's not an index tho, it's an offset.

1

u/adamrichardlimb 9d ago

An offset is an index, the index is equal to the offset/item_size. That's why we use 0-based indices to begin with.

→ More replies (4)

5

u/initial-algebra 10d ago

One-based indexing is a mistake. It comes from the confusion of ordinal ("first") and cardinal ("one") numbers. How often do you actually use a literal index in real code, anyway? Who cares if a[5] is actually the sixth element, not the fifth? In practice, all that happens is you end up having to be extra careful to add and subtract 1 all the time, whereas zero-based indexing just works.

2

u/nmsobri 9d ago

the reason indexing start at 0 and not 1 is because of pointer arithmetic. if you start with index 1, u merely skip the first element at base pointer address

0

u/hopingforabetterpast 6d ago

This is a moot point when discussing a language that abstracts over pointers.

1

u/nmsobri 5d ago

skill issues..

1

u/hopingforabetterpast 5d ago

How?

I am team 0 but how is that an argument that applies to languages that abstract over pointers?

2

u/Different_Water7545 9d ago

If you use 1 may your pillow be eternally warm and wet

2

u/JollyJuniper1993 10d ago

There‘s a very simple rule.

Is your language supposed to be for anything related to mathematics: data analysis, scientific computing, proof assisting etc? Then you index with 1.

Is your language supposed to be for anything else? Then you index with 0.

3

u/nybble41 10d ago

Mathematics doesn't consistently start with 1 either. For example initial time is generally t₀, not t₁, and the modern definition of the Fibonacci sequence starts with F₀ = 0 and F₁ = 1. If anything, mappings from the natural numbers are more common than mappings from whole numbers—especially if you discount conventions which predate the discovery of the significance of zero in number systems.

2

u/JollyJuniper1993 9d ago

Indexing of sets starts with 1 because it also counts the elements of a set, which is what matters in this context.

→ More replies (4)

1

u/personalityson 9d ago edited 9d ago

ALL languages used in math/statistics use 1-indexing: Fortran, R, SAS, SPSS, Stata, Matlab, Mathematica, Maple, Julia, Scilab

4

u/nybble41 9d ago

The subject was actual mathematical notation, not math-adjacent programming languages.

Fortran doesn't even really count here since the lower bound is configurable; you can start arrays from 0 if you want.

3

u/personalityson 9d ago

You can, but default is 1

3

u/personalityson 9d ago

While we're at it, most of the "math-adjacent" languages use column-major array layout (a vector is a column, not a row). Somehow these two things go hand in hand: 1-indexing and column-major arrays

C/C++ familiy and cargo-cult languages which copy them: 0-indexing and and row-major arrays

1

u/Inevitable-Ant1725 10d ago

pi based indexing.

1

u/Stunning_Ad_1685 7d ago

There are so many other numbers. Why only consider these two?

1

u/xpusostomos 7d ago

As a low level construct, 0, because that's the implementation. As a high level construct, neither, let the user tell you def foo[3..20]

1

u/dcbst 7d ago

Why one or the other?

Take a look at Ada, it has anything you want based indexing!

Sometimes zero based makes more sense, sometimes 1 makes more sense and sometimes you want to index with enumeration values which could have any value. In Ada you can indeed from -10 to 10 for example.

One of the biggest sources of software bugs is down to array indexing errors because the language dictates a start index. Take that restriction away and you instantly solve a huge number of bugs!

1

u/Difficult_Paint3162 7d ago

Who is your target audience? Developers? We are very used to 0 based indexing. If you are writing something for non developers/programmers 1=based might make more sense....

1

u/julka-kowal 6d ago

42-based indexing because why not

1

u/manon_graphics_witch 6d ago

0-based indexing because it simplifies indexing math.

1

u/rsclient 6d ago

VB used to have a way to let people specify the range on an object-by-object basis. It was absolutely horrible because you couldn't reason about your arrays without double checking them :-(

Everyone has settled on zero-based arrays. Unless you really need to be compatible with something, that's the way to go.

1

u/DerekRss 6d ago

You don't need to use either. If your language declares the upper and the lower bounds of arrays, you can leave the choice to the user.

For instance a declaration like

integer A(0:1000, -4:3);

Leaves the choice up to the user and no room for doubt.

1

u/pannous 6d ago

in warp we have a type index that starts from zero and a type position that starts from one they are addressed by different syntax square brackets for index and # for position

1

u/MarsupialLeast145 6d ago

Code got a lot easier for me once I stopped fighting 0-based indexing. I can't imagine ever working with 1-based.

1

u/deaddyfreddy 6d ago

is really human readable, English-like

I don't think it's a good idea.

Speaking of the base, it doesn't matter that much. Most of array/list processing is map/filter/reduce/etc anyway.

1

u/soundman32 6d ago

How about not allowing any kind of indexing? It's an advanced topic (for beginners) so why even bother implementing it, if it's too complex.

Do you have a good use case for indexing, other than 'other languages have it'. String splicing on things like substrings would be OK, which don't require the user to find an index.

1

u/Prestigious_Boat_386 5d ago

I strongly prefer 1 indexed because that's how we count but it doesn't really matter because you should just have methods for the index ranges you want anyway and you can do things like OffsetArrays.jl to let the user use their preffered system while working with things that are based on the other system. I really like having start and end sugar for ranges that get replaced with calls to firstindex and lastindex methods.

The offsetindex type from that package lets me use zero indexed opengl indices while doing everything in a one based language.

1

u/eudyptes 5d ago

Let the programmer specify both low and high bound so the programmer can choose. I believe PL/1 did this.

1

u/SnooPets5564 5d ago

-1 based

1

u/Rogntudjuuuu 5d ago

Take inspiration from Pascal and leave the decision to the programmer.

1

u/plastic_eagle 5d ago

1 based, but have the indices go downwards. 0 is the second element. -1 the third. With this, you could take over the world.

"The biggest question I have"

This cannot, *cannot*, be the biggest question you have.

1

u/DefaultAll 5d ago

I love Lua and its 1-based indexing but would recommend 0-based indexing just because everyone gets so worked up about it.

1

u/Fabiolean 5d ago

If you don't choose 0-based indexing all the nerds are going to scream at you for violating convention and impacting inter-op, and they'll be right to do so.

If you don't choose 1-based indexing you'll be objectively incorrect.

1

u/dashingThroughSnow12 4d ago

GulfOfMexico (formally known as DreamBerd) uses -1 indexing.

1

u/tobega 4d ago

If you are making a language for humans to count with, start with 1.

If you are making a language where mathematicians need to do a lot of arithmetic on indexes, consider 0.

Or you allow anything. Sometimes you need an array that starts at -5 or at 102.

2

u/spaceLem 3d ago

Just to point out there, most languages used by mathematicians, e.g. R, Julia, Matlab, Fortran, Maple, Mathematica, and Maxima, are all 1-indexed.

From my experience, most of them have tools that make indexing easy, and you'll rarely need to use manual indexing beyond really simple lists.

1

u/tobega 3d ago

Exactly! I should have said "programmers"

1

u/taysongoodmansen 4d ago

If you want to focus more on easy design and friendliness, 1 will be better, like how in scratch the indexes begin at 1. But if you want easier array manipulation 0 will be better and thats why its even 0 for most languages. Cause in scratch it was common to see people minus one, do math, and then add one back at the end whenever arrays were used, which was them just forcefully undoing the start at 1.

1

u/pgaidis 3d ago

What about string length

1

u/LoreBadTime 3d ago edited 4h ago

[This text has been randomized: complex]

finish begin light salt cake particle storm yellow white paper surface modern street sunrise metal satellite white

1

u/Aoyaba-Poett 3d ago

What about -1?

1

u/newb1029384756 10d ago

It doesnt really matter, but make it consistent.

1

u/Filgas08 10d ago

I vastly prefer 0 indexed languages because they better relate to pointers.

1

u/Toothpick_Brody 9d ago edited 9d ago

You should pick 0-indexed. The reason is that it creates a symmetry with functions from the natural numbers. They start at 0, so so should lists 

The counterargument I’ve seen is typically “in real life you start counting at one”, but this is a weak argument. What you start counting at really depends on what you’re counting. If you’re counting temperature then not only might you include zero but also negatives 

1

u/Difficult-Value-3145 9d ago

I'd use 0 go with C although lua is 1 based and that kinda is nice until you want to pass an array from C or bash or something

1

u/WalFEstelist 7d ago

I like the 1-based indexing. If I had to create my own programming language (and I actually did), I would choose exactly this. Nowadays in modern programming languages lists are no longer stored the way they were stored in C, so using 0-indexing is just a useless tradition

1

u/qwyss 7d ago

My argument for 1 is that the sort of people who want it to be 0 can cope with that.

Where as the sort of people who want it to be 1 are not the sort of people who can cope with it being 0.

So although 0 is "technically" better, 1 is a more humane design decision.

-1

u/whereswalden90 6d ago

How about neither? Well-written programs should primarily use only homogenous collections that are iterated over, not indexed into. The only reason a well-written program might use indexing should be with heterogeneous collections, which should be fixed-length tuples, and if your language has maps/objects/dicts then there's not really a strong reason to support tuples.

Especially if your language is targeted at newbies, then getting them comfortable with iterating over collections is way more important than supporting indexing.

If you feel like you need to include a function that gets the nth item of a collection, it doesn't really matter whether that function calls the first item 0 or 1, as long as it's clear about it in the function's documentation. (Though i could see an argument for the first item being 1)

2

u/ih-shah-may-ehl 6d ago

So if you have to retrieve a specific item from a collection, you have to iterate through god knows how many items instead of being able to say 'this one'?

Especially when doing calculations or data analysis / processing, indexing is critical.

1

u/Chaotic_Corvus_Corax 6d ago

Crazy how different use cases are. I am working on physics simulations and ODE optimization and I would die if there were no indexes in whatever language I use.

1

u/ih-shah-may-ehl 6d ago

Most of what I do (hobby, I am more in an expert / high level job these days) has to do with raw win32 API, DCOM marshaling and things like that. Indexing and pointer arithmetic is the only way to fly

1

u/whereswalden90 6d ago

I guess it depends on your use case. In my work I’ve almost never needed to retrieve an item from the middle of a collection by index. Usually I need to get the first or last item, or maybe the first n where n<5, or I’m finding an item by value which requires iterating anyways. I tend to use functional languages and work on the level of business logic though, I infrequently am implementing high-performance algos like quicksort from scratch.

1

u/nacnud_uk 6d ago

Why would you remove simple look-aside tables? Increasing an integer to iterate is a great way to learn the disconnect between variables and how variables can be used.

1

u/whereswalden90 6d ago

I guess it depends what domain you work in. I've never used a look-aside table in my entire career, I work primarily in high-level functional languages.

1

u/whereswalden90 6d ago

Also most mainstream programming languages have spent the last decade trying to encourage developers to stop using index-based iteration over collections, that's the last thing I'd want to introduce a newbie to.

Examples: JS for-of, Java & C# for-each, Python's iterators, Rust's iterator-returning methods, C++ range-based loops...

0

u/marshaharsha 6d ago

Lots of good programs use indices: anything to do with stencils or sliding windows or dynamic programming. Even quicksort. 

2

u/whereswalden90 6d ago

You don’t need indices to do sliding windows or dynamic programming. A functional impl for sliding windows returns a collection of windows (often lazily).

0

u/chkno 9d ago

Zero:

Consider storing groups of things. For example, suppose I'm storing points in space—(x,y,z) triples in a flat list.

In zero-based indexing, the i-th thing's values are at 3*i, 3*i+1, and 3*i+2; elegant and simple.

In one-based indexing, the i-th thing's values are at 3*i-2, 3*i-1, and 3*i. Why? Because you're kind of converting to zero-based indexes, doing the zero-based indexing thing, and then converting back to one-based indexes: 3*(i-1)+1, 3*(i-1)+2, and 3*(i-1)+3.

It gets even worse when your elements aren't uniform sizes (for example, unpacking structs from an array of bytes). You end up pretty explicitly needing to calculate with zero-based indexes and offsets and handling the conversion to the one-based indexing convention only as you first and last touch the indices.

(Any time your array element type is larger than a byte, you are implicitly storing groups of bytes, so underneath this groups-of-things-in-a-flat-list is the norm, not the exception.)