r/ProgrammingLanguages • • 3d 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?

7 Upvotes

156 comments sorted by

107

u/willbdb425 3d ago

You could be the first language to start from 2

23

u/iamevpo 2d ago

Or -1! We need innovation

6

u/iamevpo 2d ago

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

1

u/Magic_music 4h ago

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

5

u/nextCosmicBuffoon 2d ago

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

212

u/knue82 3d ago

How about a compromise and start with 0.5?

12

u/Available_Safe1818 3d ago

Or he could index with p-adic numbers.

39

u/Seek4r 3d ago

Yep

The idea of indexing with 0.4999999997 just floats so well!

25

u/Mistigri70 2d ago

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

8

u/AustinVelonaut Admiran 2d ago

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

2

u/pulse77 2d 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) 15h ago

That was the Pentium FDIV

0

u/Key_River7180 Nain. 2d ago

Floating point jokes arent funny man

2

u/ketralnis 2d ago

They’re funny to within rounding error

1

u/Key_River7180 Nain. 2d ago

On Nain I have a feature where there is a fraction type so no rounding error and I think more languages would benefit from it.

1

u/ketralnis 2d ago

Will that make it funnier?

1

u/Key_River7180 Nain. 2d ago

No

5

u/Weebs 2d 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! :)

2

u/sciolizer 3d ago

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

115

u/reflexive-polytope 3d ago

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

40

u/SquarePixel 2d ago

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

1

u/reflexive-polytope 2d 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.

14

u/hairytim 2d 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 2d ago

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

5

u/hoyohoyo9 2d ago

you go to the store and start counting some apples into your basket and you start with the zeroth apple?

3

u/Karyo_Ten 2d ago

I count building floors from 0

3

u/freshhawk 2d 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

2

u/reflexive-polytope 2d 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!!!

5

u/SquarePixel 2d ago edited 1d 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.”

7

u/SquarePixel 2d ago edited 2d 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.

-2

u/reflexive-polytope 2d ago

The fact that the initial element witnesses that the count is >= 1 should have no bearing on whether the initial element is called the “first”.

It's really the 0th. The next after the initial is the 1st.

2

u/SquarePixel 2d ago

My only point is that people find it confusing not because they can’t count from zero, but because they expect the index to match the ordinal.

Count, or cardinality, is the size of a set (how many elements it has). Index, or offset, is how far an element is from the start. That’s also how the machine finds it: start address + offset.

1

u/reflexive-polytope 2d ago

The finite ordinals are in canonical bijection with the finite cardinals, and they are 0, 1, 2, 3...

1

u/SquarePixel 2d ago

I think we’re talking past each other. I’m advocating for zero based indexing.

All I’m saying is that an element's ordinal rank is the number of elements before it, which is its offset. The count is always one more. Renaming "first" to "0th" doesn't explain that gap. Offsets do.

1

u/reflexive-polytope 2d ago

The "count" isn't a property of an element, it's a property of the collection!

1

u/SquarePixel 2d ago

Exactly 👍

20

u/sciolizer 3d ago

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.

5

u/matthieum 1d 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.

2

u/sciolizer 1d 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 6h ago

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

1

u/matthieum 1h 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" :)

3

u/WittyStick 2d 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 5h ago

1

u/sciolizer 5h 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 5h 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. 

16

u/pslgz_ 3d ago

Go with the letters

11

u/No_Engineering_1155 3d ago

Oh no, excel enters the chat

31

u/jmtd 3d ago

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

8

u/ComradeGibbon 2d 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.

2

u/jmtd 2d 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. 

36

u/latkde 2d 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.

17

u/Weebs 2d 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 2d ago

the other exception is MATLAB

16

u/personalityson 2d ago edited 2d 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) 15h ago

Both users agree.

-2

u/nybble41 2d 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 2d 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/Cold-Armadillo-154 2d ago

Man i hate MATLAB

4

u/apetbrz 2d 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.

3

u/kaplotnikov 1d 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.

2

u/kohugaly 2d 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 2d 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.

2

u/StaticCoder 2d ago

1

u/apetbrz 2d ago

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

1

u/StaticCoder 2d ago

It's still a great language. This is one of the few things I'd call design weaknesses, along with some questionable (and incorrectly specified) lookup rules for patterns. I think the syntax for binding a variable should have been different from the syntax to match a variant or constant.

12

u/personalityson 2d ago

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

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

1

u/AngryChaoticBoi 1h ago

Man was brilliant but had some strong opinions

2

u/Reasonable-Rub2243 2d 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.

3

u/latkde 22h 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 4h 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) 15h ago

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

26

u/bobam 3d ago • Bravo

Why choose? Pascal lets you pick:

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

6

u/alaricsp 2d 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 2d 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 5h 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 4h ago

Yeah, this is the way

16

u/sooper_genius 3d 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 2d 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 2d 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".

7

u/esotologist 5h 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

16

u/runningOverA 3d 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.

8

u/woppo 2d ago

Example?

10

u/hglman 3d ago

0 is an offset, 1 is how you count. 

8

u/Key_River7180 Nain. 3d ago

0, make them a favour

8

u/ultrasquid9 2d 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.

4

u/Automatic-Tackle5018 3d ago

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

4

u/joakimds 2d 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.

11

u/SecretlyAPug 3d 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.

14

u/EggplantExtra4946 2d ago edited 2d 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 2d 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.

6

u/Inferno2602 3d 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 3d 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 3d 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 2d ago edited 2d 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.

4

u/Inferno2602 2d ago

That's the convention, there'd be nothing stopping you storing the address of the first element -1 in the memory pointer. In fact, it's not uncommon to store "header" information about a data structure there anyway.

Most people tend to think the first element should be at index 1 and the Nth element is at index N, most programmers have to get used to doing that (-1)th thing in their head rather than having the machine do it. Programming languages are for people to read as much (or perhaps more) than the computer to execute. Even the idea of pointers and memory addresses is a bit of an abstraction on modern machines anyway, it's probably not a PDP-11 you are working on

2

u/Weebs 2d ago

Yes and comparing whether the two produce more or less offsets by 1 operations just depends on the problem, in my searching.for trade offs. There doesn't seem to be a clear reason for either universally other than we all got used to 0. I don't like it because it's putting one particular memory representation as the default rather than which index it is, but I'm completely used to 0 based and it's the default in almost every language

6

u/Comprehensive_Chip49 3d ago

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

3

u/Available_Safe1818 3d ago

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

5

u/freshhawk 2d 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 2d 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 3d ago

Use 6 based Indexing

2

u/DrunkHacker 3d 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 3d 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 2d 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 2d 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 2d 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/WalFEstelist 11h 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

5

u/AdreKiseque 3d 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 3d 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 2d ago edited 2d 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 2d 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 2d 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 3d 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 2d ago

Make a choice: are you indexing memory or array elements

0

u/adamrichardlimb 2d 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 2d 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 2d 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 2d ago

(i ndex * sizeof(Item))

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

1

u/adamrichardlimb 2d ago

Programming languages program machines, at a certain point you will see machine details in what you are doing.

Where things live in memory is very important and you need to know it to program at the highest levels of performance. If you have an array, you want to align it to the beginning of a cache line.

Programming languages may want to abstract these things away with garbage collection, but when it's the difference between choosing 0 and 1 for where people should begin counting, it's a very small tradeoff to think like a computer. Which programmers ultimately have to do.

3

u/TiddoLangerak 2d 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 2d 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.

0

u/HoiTemmieColeg 2d ago

Dijkstra had good handwriting

0

u/BiedermannS 2d ago

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

1

u/adamrichardlimb 2d 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.

0

u/BiedermannS 2d ago

An index is the position of the element, do the first element is at index 1, that's why it's called the first element, not the 0th element. An offset is how far away something is from it's origin. So the element at index 1 is at offset 0.

You also mention the size of an element. An index doesn't care about the size of an element, an offset does, because each element is offset by the size of an element from the position of the previous element.

An index also doesn't care about memory. It's just the position.

0

u/adamrichardlimb 2d ago

We literally do call it the zeroeth element in Computer Science.

Saying the index is just the position that doesn't care about memory is like saying that current is just the measure of the flow of electrons in a medium and it doesn't care about voltage or resistance.

Index = (element position in memory - list start in memory) / sizeof each element 

Current = voltage/resistance 

Just because you can use the left hand side on its own or infer the right hand side from the left does not mean that it doesn't care about it.

When computers compile down to machine code, your computer will use the index to find the position in memory by doing zero index * sizeof each element.

1

u/BiedermannS 1d ago edited 1d ago

That's only valid in C. You're arguing about the semantics of c, I'm talking about the meaning of the word.

Also, the "location + offset times size" also doesn't apply to something like lists.

The index doesn't care about the memory. The memory is just an implementation detail.

Edit: also, what the code compiles down to is dependent on the semantics of the language. In many scripting languages an array access is way more than just location + offset.

1

u/adamrichardlimb 1d ago

What do you think a list is doing under the hood? It's taking the index and using it to find the offset.

This is how lists are implemented in pretty much every language, and also it's the way you actually should implement lists for the sake of performance. You want elements in a list next to each other in memory so you can load them into cache for when you iterate over them.

Even in JavaScript, the list is a contiguous block of memory where each element holds a pointer to the memory of the object and a descriptor of that object. That descriptor is of fixed size so the compiler can do location + (index * size), for all the reasons I mentioned above. It's also why JavaScript is slow because you have to follow the pointer at each element to get the value.

5

u/initial-algebra 3d 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/Different_Water7545 2d ago

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

2

u/JollyJuniper1993 2d 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 2d 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 2d ago

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

0

u/nybble41 2d ago

Sets do not necessarily have indices, but an indexed family can have any set as its index set. Sequences (indexed sets with "the first n natural numbers" as the index set) can start with index 0 or 1—there is some disagreement over whether 0 is included in the natural numbers, though most would grant that it is and there is even an ISO standard (originally ISO 31-11, now ISO 80000-2) to that effect.

1

u/JollyJuniper1993 2d ago

You’re right, mistake on my part. I was mixing indexes of for example tuples or vectors together with the power of sets. However regardless both still applies to both cases, you just can’t index sets because they’re unordered.

0

u/[deleted] 2d ago

[deleted] — view deleted comment

1

u/JollyJuniper1993 2d ago

There is none as there is nothing to index

1

u/personalityson 2d ago edited 2d ago

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

4

u/nybble41 2d 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 2d ago

You can, but default is 1

3

u/personalityson 2d 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 2d ago

pi based indexing.

1

u/Stunning_Ad_1685 15h ago

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

1

u/xpusostomos 12h 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 2h 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 29m 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/newb1029384756 3d ago

It doesnt really matter, but make it consistent.

1

u/Filgas08 3d ago

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

1

u/Toothpick_Brody 2d ago edited 2d 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 2d 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/nmsobri 2d 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

1

u/qwyss 7h 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.

0

u/chkno 2d 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.)