Pixel indices should start at 0 or at 1?

Although I know what people will probably say… I still wanted to post this question. I don’t think it is a silly thing to post.

I would like to know what is the most common way of writing the following method.
Imagine i have a method to get the ID (or index) of a pixel, for example to store what pixels i have modified on an image.

``````int getPixelID(int x, int y) const {
return ( x + y * width );
}
``````

If I use the above method and i want to get the last pixel (last row last column) i will do:

``````pix.getPixelID(pix.getWidth() -1 ,pix.getHeight() -1);
``````

but to me it seems a lot easier to read:

``````pix.getPixelID(pix.getWidth(),pix.getHeight());
``````

same way, first pixel (first row first column) seems better (to me) like this:

``````pix.getPixelID(1,1);
``````

So what is more common?
what implications would have to use indices at 1?
I always thought that starting indices at 0 is totally wrong… because my first item will never be my 0th item… I know in C, C++ indices start at 0 for a good reason.

Is there any case where it makes sense to switch from indexing at 0 instead of at 1?

there’s lots of calculations you can do with indices where having the first one being 0 makes things so much easier than using 1. for example how would the getPixelID method you post, look like if you had 1 based indices?

with

``````int getPixelID(int x, int y) const {
return ( x + y * width );
}
``````

1,1 will return width+1 which is not correct, you would need to do x+(y-1)*width, when you try to do more complex calculations things get really hard if indices start at 1.

As another example, looping through a sequence of indices using modulo won’t work as well when indices start at 1, instead of x%total you would need to do something like: x%(total+1)+1 and i’m not even sure if that’s right : )

there’s lots of examples where using 1 as first index makes it so much harder and error prone. the only language i remember where arrays started at 1 was in old versions of visual basic and even they changed it in later versions to be 0 based

Also, for me personally it makes more intuitive sense to remember that the number you feed into the array is an offset, not a name.

So index 0 is “the start of the image + 0 pixels”, not “the 0th pixel”

Your mileage may vary

1 Like

Thank you for answering!
True, modulo wouldn’t work… and that’s not good…
I like the idea of offset instead of item number!