4

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)

TylerH
  • 20,799
  • 66
  • 75
  • 101
Semetg
  • 129
  • 2
  • 8
  • 26
    Array indexes start at 0 in c and c++. Pretending otherwise is wasteful at best. I would be wary about anything your teacher tells you about the language. – François Andrieux Dec 14 '17 at 19:19
  • 11
    Wow that's a terrible idea. Don't do that. – miradulo Dec 14 '17 at 19:22
  • 11
    Agreed - this implies that the teacher is, at best, uncomfortable working in C. At worst, s/he doesn't know what s/he is talking about. – Oliver Charlesworth Dec 14 '17 at 19:22
  • 1
    Please teach your teacher to drop his/her bad habits and also convince her/him to use `std::array` and/or `std::vector` rather than C-style arrays - there's really no good reason to do otherwise in modern C++. Teaching using C-style arrays *and* teaching indexing starting at 1 rather than 0 is doing students a disservice *big time* - that's going to bite some people *hard* at some point. Bad teacher - no cookie for you! – Jesper Juhl Dec 14 '17 at 19:23
  • 1
    @JesperJuhl I've tried doing that, but he is theoretically teaching us c++, and the only thing we're using from c++ are std::cin and std::cout... I've tried to tell him about STL but he doesn't know any of those things... – Semetg Dec 14 '17 at 19:26
  • 1
    @Semetg Reommended read: https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr Don't trust so called _c++ teachers_ at all. – user0042 Dec 14 '17 at 19:27
  • @Semetg If that is the case, you should seriously reconsider taking that class – Passer By Dec 14 '17 at 19:29
  • @Semetg My advice would be to ignore that teacher, buy a few [good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list) and just learn on your own. Get involved in a few C++ Open Source projects that you care about as well, to get some real life practice. You'll learn more/better that way. – Jesper Juhl Dec 14 '17 at 19:30
  • @JesperJuhl Depends on the importance of the marks one gets from that teacher... – Eugene Sh. Dec 14 '17 at 19:31
  • @Eugene Sh. - pfffth. Who cares? Once you are out of school and have a few years of real work under your belt, that matters less than nothing. Nobody ever learns to code while in school *anyway* and we all know the greenhorns just out of uni need to be trained from scratch anyway.. – Jesper Juhl Dec 14 '17 at 19:34
  • @user0042 I've got to go to this class until the school year finishes... Anyways, I thought he was dumb from the first lesson, when I taught him what uniform initialisation is.... – Semetg Dec 14 '17 at 19:36
  • 1
    @Semetg When I started to learn c++ and OOP in the late 80ies of the last millenium, I must have been lucky with an extremely competent teacher, who never bothered us with _pointers_ or _raw arrays_, and was a `const` fanatic. Looks like _SIEMENS_ provided premium quality education these days. But what questions I'm reading here almost daily regarding that stuff seems to indicate an overall poor education standard nowadays. – user0042 Dec 14 '17 at 19:43
  • @JesperJuhl How can I get involved in C++ Open Source Projects? I'd love to do that, as the only thing we currently do in school is math, but written in c++ – Semetg Dec 14 '17 at 19:44
  • @Semetg The issue that I see almost all the time with starting the index at 1 and oversizing the array are off-by-one errors, either 1) on the left-end (at 0) where the `0` index was supposed to be ignored, but used anyway, thus messing up whatever results were expected, and 2) on the right end where the loops go to index 101 instead of 100. Anytime you see code trying to fake 1-based arrays, always be wary that one of these two issues (if not both of them) may exist in that code. – PaulMcKenzie Dec 14 '17 at 19:45
  • @user0042 well I don't want to offend anybody, but good programmers usually don't end up in a small city teaching kids wrong things... – Semetg Dec 14 '17 at 19:45
  • @Semetg _"How can I get involved in C++ Open Source Projects?"_ Get something from GitHub, improve it, and do a _pull request_ . – user0042 Dec 14 '17 at 19:45
  • Finding a open source project: Start with a tool you use or are interested in, then give their forums and news groups a read through. You can learn a lot from the group's culture from they writings and some don't cotton to newbs well or have other issues that may make the project a poor place to learn. – user4581301 Dec 14 '17 at 19:47
  • @Semetg _"but good programmers usually don't end up in a small city teaching kids wrong things..."_ Sounds sad, but I actually know such people teaching at our local university. – user0042 Dec 14 '17 at 19:47
  • @Semetg "How can I get involved in C++ Open Source Projects?" - Find something you are interrested in, read their mailing-list/forum/whatever, use the code, find areas to improve, send pull requests/patches. Some things you could start out looking at: [SFML](https://www.sfml-dev.org), [boost](http://www.boost.org), [Thor](http://www.bromeon.ch/libraries/thor/), [Qt](https://www.qt.io) - all useful C++ libraries with friendly communities. – Jesper Juhl Dec 14 '17 at 19:56
  • 1
    @ChristianGibbons then let me tell you that he also doesn't leave any spaces between operators and his code looks like a huge mess, he declares all of his variables globally, because he's too lazy to write int x = 0, oh and he told us to prefer using while than for because it's easier to read, and I don't even wanna talk about the fact that he doesn't know any functions from any standard library other than and – Semetg Dec 14 '17 at 19:58
  • @user0042 The long-defunct (Crom. 15 years. Where'd the time go?) Technical University of British Columbia hired from industry and paid industry wages to attract real-world professionals to mix in with conventional educators. It was a very interesting experience, and I was surprised how effective it was. – user4581301 Dec 14 '17 at 20:00
  • @Semetg -- Probably your teacher only knows 1 (or more) of the languages that start the index at 1, and making the mistake of trying to retrofit C++ into behaving like those languages. [Here is a table of the various languages and how they index arrays](https://en.wikipedia.org/wiki/Comparison_of_programming_languages_%28array%29) – PaulMcKenzie Dec 14 '17 at 20:01
  • @PaulMcKenzie he told us he learnt C, but I don't know how in the world can you be this disinterested in what you teach, that you don't even know the basics... – Semetg Dec 14 '17 at 20:03
  • @Semetg -- Well they may have learned `C` and in the process tried to retrofit `C` into one of those languages listed in the table that they may have learned prior to learning `C`. Probably thought it was a neat idea, but it is wrong-headed. – PaulMcKenzie Dec 14 '17 at 20:04
  • @user4581301 I'd be happy if these people would even be open to their local professionals here. I would give them some advice what's actually necessary to be taught, to avoid _brain washing_ their alumni, before I can unleash them to my production code. – user0042 Dec 14 '17 at 20:06
  • 3
    @Semetg _"he told us he learnt C"_ And even with C, that array indexing idiom is blatantly wrong. – user0042 Dec 14 '17 at 20:07
  • @user0042 yeah but you're really passionate about what you're doing, he doesn't seem to care – Semetg Dec 14 '17 at 20:08
  • 1
    @user0042 Just link them to https://youtu.be/YnWhqhNdYyk. It should be required viewing for all professors teaching C++. It’s not good enough for *this* professor, who should not be teaching C or C++ at all, but it’s good enough for a lot of the problems. – Daniel H Dec 14 '17 at 20:09
  • 1
    @Semetg _"yeah but you're really passionate about what you're doing"_ Well, that's what I'm living from, I wonder what he does :-/ – user0042 Dec 14 '17 at 20:09
  • @DanielH LOL :-D!! If you read closely, this video link already appears in my (above mentioned) question: **[Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++?](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr)** – user0042 Dec 14 '17 at 20:14
  • @user0042 Oh, you’re right. I did miss that bit of your question just now. Although, now that I think about it, that might have been where I saw the video in the first place. – Daniel H Dec 14 '17 at 20:21
  • @DanielH Do you think I should make it more prominent in my question? I'll try that ... – user0042 Dec 14 '17 at 21:12
  • @user0042 I think it makes sense where it is, as part of the motivation for asking the question. I just missed it this time because I had seen the question before and didn’t read it as carefully as I had the first time, and forgot that it had the video linked in it. – Daniel H Dec 14 '17 at 21:15
  • Let us [continue this discussion in chat](http://chat.stackoverflow.com/rooms/161240/discussion-between-user0042-and-daniel-h). – user0042 Dec 14 '17 at 21:17
  • 1
    @Semetg: Every reasonable C or C++, Python, etc. programmer expects an array to start at `0` as defined by the language. Not following this ideom makes your code behaving unexpectedly, hence violating a very fundamental and well accepted [_principle of least surprise_](https://en.wikipedia.org/wiki/Principle_of_least_astonishment). One problem with that is it makes your code error prone and harder to understand. Not only for other, but also most likely to you. It also causes problems with libraries, as these typically follow such language ideoms. – too honest for this site Dec 14 '17 at 21:19
  • @Olaf I asked because at first I couldn’t find any disadvantages of using this method and starting from one to make using indexes easier seemed pretty smart :)) – Semetg Dec 14 '17 at 21:25
  • Well, I voted to reopen (which happens very rarely). Let's see if @user0042 has a good answer. "starting from one to make using indexes easier seemed pretty smart" - it actually is the opposite. In programming starting at `0` is a good idea. A simple example is a ring-buffer where you can generate the next index by simple modulus. FYI: Pascal allowed arbitrary indexs from start. The successor, Modula did not and use `0`-based indexing. The rational of N. Wirth was the arbitrary index-borders were too confusing and lead to code being harder to read. Plus the advantages of 0-based indexes. – too honest for this site Dec 14 '17 at 21:29
  • @Olaf lol maybe – Semetg Dec 14 '17 at 21:34
  • @Olaf ooh, maybe the teacher has a bunch of `#define`s for Roman Numerals to decimal. – Christian Gibbons Dec 14 '17 at 22:50

3 Answers3

17

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.

Slava
  • 43,454
  • 1
  • 47
  • 90
2

Arrays in C++ and C are zero indexed, meaning the first array element is numbered with 0 and the last element is numbered with N-1 when accessed via subscript operator[]. As-is your code skips the first array element that is the a[0] and starts off with a second element that is the a[1] so you should avoid that practice.

Ron
  • 14,674
  • 4
  • 34
  • 47
  • I know that's the accepted way, but I wanted to know if what my teacher was doing something which was also considered correct... Apparently I should teach him... – Semetg Dec 14 '17 at 19:29
  • 1
    @Semetg It is considered a really, really, really bad practice to do this in fact perhaps the worst practice except maybe dangling pointers or free floating pointers – Jake Freeman Dec 14 '17 at 19:35
  • @JakeFreeman oh ok I didn't think it was this big of a deal but you guys are right, doing that basically breaks every mechanism related to arrays in c++... – Semetg Dec 14 '17 at 19:41
  • 2
    @Semetg be careful what you teach teachers. They are also markers and some have very frail egos. – user4581301 Dec 14 '17 at 19:41
  • 1
    Also; `.empty()` on any container will be basically useless since you'll always have one extra element in there. And same for `.size()` where you'll always have to subtract one. There are *so many* ways this is a horrible idea. – Jesper Juhl Dec 14 '17 at 20:10
  • Despite my former comment to another post about wasting memory, that is the least problem in terms of writing good, maintainable and readable code. – too honest for this site Dec 14 '17 at 23:09
-1

What is size of integer?

The size of an int is really compiler dependent. Back in the days when processors used to be 16 bit, an int was 2 bytes. Nowadays, it's most often 4 bytes on a 32-bit as well as 64-bit systems.

The best way of checking size of int is

cout << sizeof(int);


Assumption: sizeof(int) = 4 bytes in your architecture.

What you tell compiler?

When you declare a statement
int array[10];
You tell Compiler to reserve 40 BYTES for use(based on Assumption above.)

What you do to the allocated memory?

You are using only 9 elements (1-9) thats 36 bytes of 40 allocated wasting 4 bytes of memory. Just memory is cheap doesn't mean its free. Morever if your working with 3 dimensional arrays.
Example:

  int array[100][100][100]

You will end up losing a lot of memory I mean lot of memory that other process require but can't use just because you have deliberately reserved it and not used.

Problem with Strings.

If you are working with character arrays, you may something land up in disaster.
Example:

    char str[8];
    str[1] = 'H';
    str[2] = 'e';
    str[3] = 'l';
    str[4] = 'l';
    str[5] = 'o';
    str[6] = '\0';
    cout<<str;

There maybe situation where no output will be displayed as the str[0] may contain the NULL character.

too honest for this site
  • 12,050
  • 4
  • 30
  • 52
Zahid Khan
  • 2,130
  • 2
  • 18
  • 31
  • 1
    Memory wastage is the least of your worries. – user4581301 Dec 14 '17 at 19:54
  • Memory isn't free :( why to waste memory. – Zahid Khan Dec 14 '17 at 19:59
  • 3
    I would not downvote your answer and it is often a mystery to me why people downvote. That said, the answer would be stronger if you used the last part about the string not printing correctly as your main point and mentioned memory wastage as an aside. You do a good job explaining the memory layout part, which is a good start. From there, I'd cover the correctness issues and design errors. Then get to efficiency. The degree of wrongness in the idea in the original question is so large that refuting it is like shooting fish in a barrel. – Zalman Stern Dec 14 '17 at 20:25
  • @ZalmanStern Thanks for explaination, the downvotes one after another almost had taken my breath out. Do you think this answer deserves 3 down votes? – Zahid Khan Dec 14 '17 at 21:12
  • 1
    Well frankly, your answer is not the best answer here. I judge Slava's arguments as more important. But that absolutely doesn't mean that your answer is bad. It is correct and does by no means deserve a down vote. I gave up wondering why people vote down here some time ago. Or why a question, which absolute clearly can have (and has) only one answer (with several facets) is declared as "put on hold as primarily opinion-based" LOL. Why do people vote down? Because they can. That simple. – user2328447 Dec 14 '17 at 21:50
  • My guess: the down votes are for assuming an `int` is 4 bytes. 2, 4, and 8 are common (2 in 16-bit microcontrollers). Some DSPs don't have byte addressing; in those, sizeof(int) = 1. – Todd Fleming Dec 14 '17 at 22:54
  • 1
    @user4581301: "Memory wastage is the least of your worries" - you never programmed bare-metal embedded, did you? – too honest for this site Dec 14 '17 at 23:03
  • `NULL` is a macro with a null pointer constant. While in C++ it is typically the `0´ literal in C++, it should never be used as integer value. Actually it should not be used anymore since 6 years (C++11). It is a problematic C legacy (where it typically is `void *)0` and ideomatic to use a null pointer constant). – too honest for this site Dec 14 '17 at 23:05
  • Quite a bit of it. Spent years on the 68hc11 that I'd love to get back. – user4581301 Dec 14 '17 at 23:06
  • @user4581301: In that case I wonder why you don't care wasting memory;-) The HC11 was extremely restrictied with typically 512 octets RAM. I used that quite a lot - with Assembler, though. Yes, it was/is (still avcailable, although I now prefer ARM Cortex-M and MSP430) a nice little MCU. And it had really good documentation. Those were the days … . – too honest for this site Dec 14 '17 at 23:07
  • My point here was more general. If RAM is a concern, you'll pick off the lack faster than some of the logic errors that will result. Since that comment it looks like at a good logic error example has been added. – user4581301 Dec 14 '17 at 23:18
  • @Olaf The arguments in favour of 0 over NULL is mostly aesthetics and "personal preference". Do you think that would be a reason of downvotes? Still amended my answer. – Zahid Khan Dec 15 '17 at 06:18
  • @ToddFleming Is that Okay now? Tried my best to make it pleasing. :) and also added assumption int = 4. – Zahid Khan Dec 15 '17 at 06:47
  • @ZahidKhan: It is not. Usage of `NULL` is clearly deprecated in C++ in favour of `nullptr`. Let this aside, a `char []` definitively is not a string (it also is not in C either). It is C++, so use the proper string type. This is no way personal preference, but strongly advised. I edited your snippet to show the ideomatic and most clear way to write the null-terminator (ASCII `NUL`). I also removed the completely wrong commas and added semicolons. Please next time at least provide correct code. As there were multiple commas and no semicolons at all, I can't consider them simple typos. – too honest for this site Dec 15 '17 at 12:47
  • Your edit(s) did not really clarify anything, but just replaced some false/incomplete assumtions and statements by other such statements/assumptions. No offence, but it seems you nee to get the basics right. Btw: 16 bit CPUs are no way outdated. Nor are 8 bit CPUs. Actually both are still the vast majority of CPUs in terms of annual sales and distinct architectures. – too honest for this site Dec 15 '17 at 12:52