My teacher usually starts indexing arrays from one. So, basically, when we need an array of 100 elements he uses
int a[101]
instead of
int a[100]
and, for example, he fills it like this:
for (int i = 1; i <= 100; i++)
cin >> a[i];
Are there any problems with using this method, or should I avoid it? (I don't have any problems in working with indexes starting from 0)
Should I use this regularly, or should I avoid it?
You should avoid it. One problem is that 99.9% of C++ developers would not share this bad habit with you and your teacher, so you will find their code difficult to understand and vice versa. However, there is worse problem with that. Such indexing will conflict with any standard algorithm and others that follow them and you would have to write explicit pesky code to fix it as container.begin()
and container.end()
as well as std::begin()
and std::end()
for C style arrays to work with accordance to the C++ standard which is 0 based.
Note: As mentioned in comments for range loop, which is implicitly using begin()/end()
would be broken as well for the same reason. Though this issue is even worse as range used implicitly and there is no simple way to make for range loop work in this case.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With