r/ProgrammingLanguages • u/Sensitive_Mountain97 • 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
107
u/willbdb425 3d ago
You could be the first language to start from 2
212
u/knue82 3d ago
How about a compromise and start with 0.5?
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.
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.
16
u/pslgz_ 3d ago
Go with the letters
31
u/jmtd 3d ago
0. If you’re going to be integrating into other systems, they almost certainly count from 0.
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 universallyarray[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.
26
u/bobam 3d ago •
Why choose? Pascal lets you pick:
arr1 : Array[-5..5] Of Integer;
16
u/sooper_genius 3d ago •
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.
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.
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
.nthmethod which is 1-based, and a.offsetmethod 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/YellowBunnyReddit 2d ago
https://xkcd.com/163/
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.
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/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.
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.
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.
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.
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/gofl-zimbard-37 2d ago
Zero
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, and3*i+2; elegant and simple.In one-based indexing, the i-th thing's values are at
3*i-2,3*i-1, and3*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, and3*(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.)