r/ProgrammingLanguages • u/Sensitive_Mountain97 • 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
140
u/willbdb425 10d ago
You could be the first language to start from 2
262
u/knue82 10d ago
How about a compromise and start with 0.5?
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.
28
u/sciolizer 10d 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.
19
u/pslgz_ 10d ago
Go with the letters
33
u/jmtd 10d ago
0. If you’re going to be integrating into other systems, they almost certainly count from 0.
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 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.
28
u/bobam 10d ago •
Why choose? Pascal lets you pick:
arr1 : Array[-5..5] Of Integer;
19
u/sooper_genius 10d 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.
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.
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.
5
u/YellowBunnyReddit 10d ago
https://xkcd.com/163/
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
.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.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
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/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/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.
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.
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.
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
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.
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
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.
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/gofl-zimbard-37 10d ago
Zero
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)
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, 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.)